Haskell 添加两个列表模式匹配

发布于 2024-12-04 06:16:34 字数 314 浏览 1 评论 0 原文

所以我在 GHCI 上有以下内容

>let addlist [] [] = []
>let addlist (a:as) (b:bs) = (a+b) : addlist as bs
>let x = [1..5]
>let y = [6..10]
>addlist x y

最后一行给了我: [7,9,11,13,15*** 例外::1:5-49:函数 addlist 中的非详尽模式

我只是想将两个列表一起添加到一个列表中...:(

我做了什么 ?

错了吗

So here I have the following on GHCI

>let addlist [] [] = []
>let addlist (a:as) (b:bs) = (a+b) : addlist as bs
>let x = [1..5]
>let y = [6..10]
>addlist x y

The last line gives me:
[7,9,11,13,15*** Exception: :1:5-49: Non-exhaustive patterns in function addlist

I am merely trying to add two list together into one list...:(

What did I do wrong?

Thanks

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

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

发布评论

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

评论(3

软的没边 2024-12-11 06:16:34

请注意,如果列表大小不同,您仍然会遇到“非详尽模式匹配”问题!这是一个适用于所有情况的解决方案:

addList [] _ = []
addList _ [] = []
addList (a:as) (b:bs) = (a+b) : addList as bs

不是两个列表为空的模式!

最后一点:在 GHCi 中编写多行定义是一件痛苦的事情 - 在某些编辑器中将它们写入 .hs 文件并使用 :load MyFile.hs:reload GHCi 内部

Please not that you still have problems with "Non-exhaustive pattern-match" if the lists are not the same size! Here is a solution that works for all cases:

addList [] _ = []
addList _ [] = []
addList (a:as) (b:bs) = (a+b) : addList as bs

not the two patterns where either list is empty!

And one final note: it's a pain to write multi-line definitions in GHCi - write them in some editor into a .hs file and use :load MyFile.hs and :reload inside GHCi

给我一枪 2024-12-11 06:16:34

如果您想在 let 中使用模式匹配来定义函数,则不能像以前那样对每个模式使用一个 let - 这只会定义两个独立的函数(第二个函数遮盖第一个函数)。

您需要使用单个let,并使用换行符分隔模式,或者在不能使用换行符的ghci 中,使用分号。所以:

let addlist [] [] = []; addlist (a:as) (b:bs) = (a+b) : addlist as bs

If you want to define a function using pattern matching inside a let, you can't use one let per pattern as you did - that will simply define two independent functions (the second one shadowing the first).

You need to use a single let and separate the patterns using linebreaks or, in ghci where you can't use linebreaks, semicolons. So:

let addlist [] [] = []; addlist (a:as) (b:bs) = (a+b) : addlist as bs
书间行客 2024-12-11 06:16:34

请注意,您有一个内置函数 zipWith 用于使用给定函数按元素合并两个列表,因此您可以编写

addList xs ys = zipWith (+) xs ys

或更短的代码

addList = zipWith (+)

Note that you have a built-in function zipWith for merging two lists element-wise with a given function, so you can write

addList xs ys = zipWith (+) xs ys

or shorter

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