开发者

Erlang pattern matching with functions

As Erlang is an almost pure functional programming language, I'd imagine this was possible:

case X of
    foo(Z) -> ...
end.

where foo(Z) is a decidable-invertible pure (side-effect free) bijective function, e.g.:

foo(input) -> output.

Then, in the case that X = output, Z would match 开发者_如何学Pythonas input.

Is it possible to use such semantics, with or without other syntax than my example, in Erlang?


No, what you want is not possible.

To do something like this you would need to be able to find the inverse of any bijective function, which is obviously undecidable.


I guess the reason why that is not allowed is that you want to guarantee the lack of side effects. Given the following structure:

case Expr of
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
end

After you evaluate Expr, the patterns are sequentially matched against the result of Expr. Imagine your foo/1 function contains a side effect (e.g. it sends a message):

foo(input) ->
  some_process ! some_msg,
  output.

Even if the first pattern wouldn't match, you would have sent the message anyway and you couldn't recover from that situation.


No, Erlang only supports literal patterns!

And your original request is not an easy one. Just because there is a an inverse doesn't mean that it is easy to find. Practically it would that the compiler would have to make two versions of functions.


What you can do is:

Y = foo(Z),
case X of
  Y -> ...
end.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜