模式匹配Haskell中的等价变量,就像在Prolog中一样 [英] Pattern matching equivalent variables in Haskell, like in Prolog
问题描述
在prolog中,我们可以执行如下操作:
myFunction a(a:xs)= ...
这是,当 myFunction
与第二个参数中列表的第一项相同,该函数将评估为 ...
。
现在我的问题是......如何在Haskell中完成类似的事情?
我认为Prolog的模式匹配比Haskell更有表现力。我一直在尝试在Haskell中编写代码,而且我遇到了麻烦 - 要么是使用无效的语法,要么就是上面的技巧根本就不行。
Haskell不会做这种变量匹配。您必须明确地加以警惕:
myFunction a(x:xs)
| x == a = ...
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.
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屋!