开发者

`when` reserved word in erlang

I started off this morning trying to work out what the 'when' statem开发者_StackOverflow社区ent 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().

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜