Haskell 中的模式匹配等效变量,就像 Prolog 中一样

发布于 2024-09-30 09:41:54 字数 296 浏览 1 评论 0原文

在 prolog 中,我们可以执行如下操作:

myFunction a (a:xs) = ...

即,当 myFunction 的第一个参数与第二个参数中的列表的第一项相同时,该函数将计算为 ...

我现在的问题是...如何在 Haskell 中完成类似的事情? 我认为 Prolog 的模式匹配比 Haskell 的更具表现力。我一直在尝试用 Haskell 编写代码,但遇到了麻烦——要么我使用了无效的语法,要么上面的技巧根本不起作用。

In prolog, we can do something like the following:

myFunction a (a:xs) = ...

This is, when the 1st argument of myFunction is the same as the first item of the list that's in the 2nd argument, this function will evaluate to ....

My question now is... how to accomplish a similar thing in Haskell?
I have the idea that Prolog's Pattern Matching is more expressive than Haskell's. I've been trying to code that in Haskell and I'm having trouble -- either I am using invalid syntax or the above trick will simply not do.

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

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

发布评论

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

评论(3

噩梦成真你也成魔 2024-10-07 09:41:54

Haskell 不做这种“变量匹配”。你必须明确地保护:

myFunction a (x:xs)
    | x == a = ...

Haskell doesn't do this kind of "variable matching". You'll have to explicitly put a guard on:

myFunction a (x:xs)
    | x == a = ...
转身泪倾城 2024-10-07 09:41:54

Haskell 不像 Prolog 那样统一变量。正如 Haskell 98 报告 所说,

与每个匹配对应的模式集必须是线性的——不允许变量在整个集中出现多次。

您当然可以命名变量,并声明它们也必须相等:

f a (b:_) | a == b = ...

有趣的是,Agda 确实让信息在这样的模式之间流动,并引入了一个特殊的符号 fx (.x:_) 来表示这个x 必须是那个x

Haskell doesn't do unification of variables, as Prolog does. As the Haskell 98 report says,

The set of patterns corresponding to each match must be linear---no variable is allowed to appear more than once in the entire set.

You can of course name the variables, and state they must also be equal:

f a (b:_) | a == b = ...

Interestingly, Agda does let information flow across patterns like this, and introduces a special notation f x (.x:_) to say that this x must be that x.

只为守护你 2024-10-07 09:41:54

在 Haskell 中,你不能在模式匹配中进行像这样的隐式比较。相反,您需要添加一个显式进行比较的防护,如下所示:

myFunction a (b:xs) | a == b = ...

In Haskell, you can't do implicit comparisons like this in a pattern match. Instead, you'll need to add a guard which explicitly does the comparison, like so:

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