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

编程入门 行业动态 更新时间:2024-10-12 03:22:53
本文介绍了模式匹配Haskell中的等价变量,就像在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中一样

本文发布于:2023-10-10 17:41:24,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:就像   变量   模式   Prolog   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!