What is begin…end in Erlang used for?

2019-04-05 02:39发布

I just stomped at a begin...end in Erlang's documentation (here), but it doesn't give some examples of how it is useful.

Looking here in StackOverflow I found two cases where people would be using begin...end, both in list comprehensions:

But I wonder if there are more of such uses.

Can anyone provide another scenario in which a begin...end is useful in Erlang?

Thanks

4条回答
叼着烟拽天下
2楼-- · 2019-04-05 02:48

Macros, for example:

-define(M(A, B),
    begin
        C = foo(),
        bar(A, B, C)
    end).
查看更多
Bombasti
3楼-- · 2019-04-05 02:52

To evaluate a catch (always the same idea to have multiple expression reduced to one)

Res = (catch
    begin
        C = foo(Bar),
        io:format("evaluation of C ok~n"),
        D = bar(A, B, C)
     end),
查看更多
一夜七次
4楼-- · 2019-04-05 02:55

As previous answerers mentioned, this construct is used whenever you need to have multiple expressions but only one is allowed.

However, the majority of such cases would be considered a stinky style. I can remember only a few of places where a single expression is expected: an argument in a function call, catch expression, case of, try of and list comprehension. All of them except for list comprehension shouldn't be used with begin end construct because the variables are leaking to the outer scope probably causing the subsequent bindings to become matches.

List comprehension expression is different because it is transformed to a separate function with its own scope and no variable introduced in begin end leaks to the outer scope.

查看更多
戒情不戒烟
5楼-- · 2019-04-05 03:02

According to erlang documentation is it block expression that evaluates each expression but returns only the last one.

See this example (not using block expression):

A = 1,
case A + 1 of
    3 ->
        ok;
    _->
        nop
end.

% returns ok

Now you can define A within the case argument using block expression:

case begin A = 1, A + 1 end of
    3 ->
        ok;
    _->
        nop
end.

%returns ok

That evaluates A = 1, then returns the result of A + 1.

Now we know that this will not work:

case A = 1, A + 1 of
    3 ->
        ok;
    _->
        nop
end.

% returns syntax error before: ','
查看更多
登录 后发表回答