例外:功能上的非穷举模式 [英] Exception: Non-exhaustive patterns in function

查看:88
本文介绍了例外:功能上的非穷举模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图创建一个功能,该功能从列表中删除重复项,并将其替换为单个元素.不断收到错误消息函数中的非穷尽模式已删除重复".我认为这意味着我的模式匹配遗漏了可能的情况?我想我已经涵盖了所有可能性.我是Haskell的新手,因此非常感谢您的帮助.

Attempting to create a function that removes duplicates from a list, and replaces them with a single element. Keep getting an error message "Non-exhaustive patterns in function removeduplicate". I assume that means my pattern matching is missing a possible case? I think I've covered all the possibilities though. I'm very new to Haskell, so any help is greatly appreciated.

removeduplicate :: (Eq a) => [a] -> [a]
removeduplicate [] = []
removeduplicate (x:[]) = [x]
removeduplicate (x:z:[]) = if z == x then [x] else (x:z:[])
removeduplicate (x:y:[xs])
    | x == y = x:(removeduplicate [xs])
    | otherwise = x:y:(removeduplicate [xs])

推荐答案

您的问题出在您的最终模式中.我以为它是要匹配所有列表的,但是您所拥有的方式是,它匹配其中包含一个元素xs的列表.

Your problem is in your final pattern. I assume it is meant to match all lists, but the way you have it, it is matching a list with one element, xs, in it.

这意味着编译器看到的是3个元素列表的匹配项,但没有看到任意长度的列表,这就是它抱怨的原因.

This means the compiler is seeing a match for a 3 element list, but not for an arbitrary length list, which is why it is complaining.

要解决此问题,请删除xs周围的框.

To fix this, remove the box around xs.

removeduplicate (x:y:xs)
    | x == y = x:(removeduplicate xs)
    | otherwise = x:y:(removeduplicate xs)

现在xs被视为列表,因此您匹配的列表至少包含 三个项目,而不仅仅是三个项目.

Now xs is treated as a list, so you are matching lists with at least three items, rather than just three items.

这篇关于例外:功能上的非穷举模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆