Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`when` reserved word in erlang

Tags:

erlang

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?

like image 692
MattyW Avatar asked Nov 10 '10 09:11

MattyW


People also ask

When clause in 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().

Which symbol is used to declare unbound values in Erlang?

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.

What is pattern matching in 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.

What is fun in Erlang?

Advertisements. Funs are used to define anonymous functions in Erlang. The general syntax of an anonymous function is given below −


1 Answers

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.

like image 128
Peer Stritzinger Avatar answered Nov 09 '22 00:11

Peer Stritzinger