5

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?

MattyW
  • 1,519
  • 3
  • 16
  • 33
  • I don't know too much Haskell but when in Haskell and Erlang are quite different from what I see in the Haskell answers. – Peer Stritzinger Nov 10 '10 at 11:04
  • 2
    I'm removing the Haskell tag, as this really has nothing to do with Haskell. You can write a function called "when" in pretty much any language. – jrockway Nov 10 '10 at 15:27
  • Might want to consider renaming the question to "`when` reserved word in Erlang" or "`when` keyword in Erlang". Erlang doesn't have statements. #Pedantic – Ray Toal Mar 01 '16 at 05:20

1 Answers1

18

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.

2240
  • 1,547
  • 2
  • 12
  • 30
Peer Stritzinger
  • 8,232
  • 2
  • 30
  • 43