It’s been a while since the last post which was a short introduction into functional programming in general and now it’s time to dive into some of the basic concepts of the language.
Single assignment & pattern matching
In Erlang we should think variables in a mathematical sense of the term, which means that once you’ve bound a variable, you cannot change its value . If you state that X is 5 , then it will always be 5 (a variable is called bound if already contains a value, unbound otherwise):
Eshell V5 . 10 . 1 ( abort with ^ G ) > X = 5 . 5 > X = 6 . ** exception error : no match of right hand side value 6 > X = 5 . 5
But this error is not exactly what we expected. In Erlang, the = operator does actually pattern matching (there are no LHS/RHS values). A pattern match is done like so:
Pattern = Expression
The Pattern consists of data structures that may contain both bound and unbound variables. The Expression part may contain data structures, bound variables, mathematical operations and function calls. If the pattern match succeeds, any unbound variables will be bound and the value of the expression will be returned. Using pattern matching we can extract data out of complex structures:
> {_, Name , Surname } = { person , "John" , "Doe" }. { person , "John" , "Doe" } > Name . "John" > Surname . "Doe" > {_, Name , "bla" } = { person , "John" , "Doe" }. ** exception error : no match of right hand side value { person , "John" , "Doe" }
We extract the name and surname and bound them to the Name and Surname variables. The second pattern match fails because “bla” does not equal to “Doe”.
Note that all variable names must begin with a capital letter.
... continue reading