在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中一样
发布评论