I started off this morning trying to work out what the 'when' statement is used for in erlang. I know the below example is wrong:
do_larger() ->
io:format("Larger~n").
do_smaller() ->
io:format("Smaller~n").
when_version(Size) ->
when Size > 10 -> do_larger(),
when Size < 10 -> do_smaller().
I decided to look at its implementation in Haskell to see if this would help and I ended up getting even more confused.
Is anyone able to point me at a tutorial (or explain to me) what the when statement is used for and how it's used in haskell and/ or erlang?
The when in Erlang is a guard on a clause. This regards the pattern matching built into Erlang. Your example must be: when_version(Size) when Size > 10 -> do_larger(); when_version(Size) when Size < 10 -> do_smaller().
In Erlang, all the variables are bound with the '=' statement. All variables need to start with the upper case character. In other programming languages, the '=' sign is used for the assignment, but not in the case of Erlang.
Pattern matching occurs when evaluating a function call, case- receive- try- expressions and match operator (=) expressions. In a pattern matching, a left-hand side pattern is matched against a right-hand side term. If the matching succeeds, any unbound variables in the pattern become bound.
Advertisements. Funs are used to define anonymous functions in Erlang. The general syntax of an anonymous function is given below −
The when
in Erlang is a guard on a clause. This regards the pattern matching built into Erlang. Your example must be:
when_version(Size) when Size > 10 ->
do_larger();
when_version(Size) when Size < 10 ->
do_smaller().
See Guard Sequences and Function Declaration Syntax in the reference.
For a tutorial read Guards, Guards! in Learn You Some Erlang for Great Good which is a great online Erlang tutorial BTW.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With