开发者

`when` reserved word in erlang

开发者 https://www.devze.com 2023-01-24 22:07 出处:网络
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:

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

精彩评论

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