Setting up the environment
Since I am working with a Mac, first step I will take is running the following command:
brew install erlang
Purpose of this post
Just sharing with other people my opinion about my brief experience with Erlang and hopefully will give other people some tips on how to start coding in this language.
Coding a basic program
Below the code which is hosted on Github
Compiling the program
The above code must be compiled so we’ll run the below command
and this will create a new file with the same name but with extension *.beam
Running the program
Once we compile the code we can run the program with the following command: erl -run poc all -run init stop -noshell
This is not a hello world program at all but not a very complicated one neither. We got a list of people (men and women) and after running the program we will only display by console a greeting to those people who are older than the average of people in the list. In case of we greeting to a woman we’ll say “Hello miss…” and on the other hand we will say “hello mister …” when greeting to a man.
To sum up the program execution will display the below:
The average age is 31 years old. Hello miss "Mariah" , you're 51 and you are older than average people Hello mister "John" , you're 33 and you are older than average people Hello mister "Mick" , you're 42 and you are older than average people
Understanding the code
Since I am not an experienced functional-programmer I try to to understand it comparing with other programming languages which I got more experience working with.
Apologize in advance for all those mistakes I will be making in my explanation.
- Module declaration: This looks like the package declaration (or namespace) in other programming languages.
- Record declaration: I am sure any Java developer would understand this like a POJO, I mean looks like If we are declaring the object structure.
- “Records constructor”: - This is like when declaring a constructor in other programming languages.
- Declaring methods / functions: I really like the idea of last line the code in a method is the response. This happens in Go or Scala (or both, don’t remember now…). word when function returning a value
- Case statement: Like in other programming languages, we as make use of this statement structure.
- Objects list creation: Very similar to other programming languages, isn’t it?
- Calling other methods/functions: Nothing to explain about it…
- Iterating over the list:: From my point of view, this is the only part which I’ve coded with a more functional-programming orientation and probably the part of code which I’ve enjoyed coding much more… As we can see, we split the method declaration in three steps: the first one assumes we receive a list of elements, the second one that we are retrieving a single element in the list, and the last one will be use to process empty lists
Code can be found on Github, click here to download it