Haskell 中的模式匹配等效变量,例如 Prolog [英] Pattern matching equivalent variables in Haskell, like in Prolog
问题描述
在 prolog 中,我们可以这样做:
In prolog, we can do something like the following:
myFunction a (a:xs) = ...
也就是说,当 myFunction
的第一个参数与第二个参数中的列表的第一项相同时,此函数将评估为 ...
.
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 ...
.
我现在的问题是......如何在 Haskell 中完成类似的事情?我认为 Prolog 的模式匹配比 Haskell 的更具表现力.我一直在尝试在 Haskell 中编写代码,但遇到了麻烦——要么我使用了无效的语法,要么上面的技巧根本行不通.
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.
推荐答案
Haskell 不做这种变量匹配".您必须明确表示:
Haskell doesn't do this kind of "variable matching". You'll have to explicitly put a guard on:
myFunction a (x:xs)
| x == a = ...
这篇关于Haskell 中的模式匹配等效变量,例如 Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!