Erlang 模式与函数的匹配
由于 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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,你想要的东西是不可能的。
要执行这样的操作,您需要能够找到任何双射函数的反函数,这显然是不可判定的。
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.
我想不允许这样做的原因是你想保证没有副作用。给定以下结构:
在计算
Expr
后,模式将按顺序与Expr
的结果进行匹配。想象一下您的 foo/1 函数包含一个副作用(例如,它发送一条消息):即使第一个模式不匹配,您仍然会发送该消息并且无法从中恢复情况。
I guess the reason why that is not allowed is that you want to guarantee the lack of side effects. Given the following structure:
After you evaluate
Expr
, the patterns are sequentially matched against the result ofExpr
. Imagine yourfoo/1
function contains a side effect (e.g. it sends a message):Even if the first pattern wouldn't match, you would have sent the message anyway and you couldn't recover from that situation.
不,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.
你能做的是:
What you can do is: