Erlang 模式与函数的匹配

发布于 2024-11-19 02:19:25 字数 323 浏览 0 评论 0原文

由于 Erlang 是一种几乎纯函数式编程语言,我想这是可能的:

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

其中 foo(Z) 是一个可判定可逆纯(无副作用)双射函数,例如:

foo(input) -> output.

那么,在X = 输出的情况下,Z将匹配为输入

在 Erlang 中是否可以使用这样的语义,无论是否有除我的示例之外的其他语法?

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 as input.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

〆一缕阳光ご 2024-11-26 02:19:25

不,你想要的东西是不可能的。

要执行这样的操作,您需要能够找到任何双射函数的反函数,这显然是不可判定的。

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.

樱桃奶球 2024-11-26 02:19:25

我想不允许这样做的原因是你想保证没有副作用。给定以下结构:

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

在计算 Expr 后,模式将按顺序与 Expr 的结果进行匹配。想象一下您的 foo/1 函数包含一个副作用(例如,它发送一条消息):

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

即使第一个模式不匹配,您仍然会发送该消息并且无法从中恢复情况。

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.

羁客 2024-11-26 02:19:25

不,Erlang 只支持文字模式!

而你最初的要求并不容易。仅仅因为存在逆元并不意味着它很容易找到。实际上,编译器必须创建两个版本的函数。

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.

死开点丶别碍眼 2024-11-26 02:19:25

你能做的是:

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

What you can do is:

Y = foo(Z),
case X of
  Y -> ...
end.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文