如何修复Haskell中的“函数中的非穷举模式"错误? [英] How to fix 'Non-exhaustive patterns in function' error in haskell?
本文介绍了如何修复Haskell中的“函数中的非穷举模式"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个函数,该函数将元组列表作为参数并按第二个元素进行排序.它不会打印其他内容,仅显示错误"***异常:main.hs:20:1-76:函数sortWords中的非穷尽模式" 这是代码:
I am trying to create a function which takes a list of tuples as argument and sort the by the second element. It doesn't print anytning else, just the error '*** Exception: main.hs:20:1-76: Non-exhaustive patterns in function sortWords' Here is the code:
sortWords :: [(String, Int)] -> [(String, Int)]
sortWords [(str,num)] = sortBy (\x y -> compare (snd x) (snd y)) [(str,num)]`
这是我调用函数的方式
main = do
putStrLn $ show $ sortWords [("friend",1),("she",2)]
我不得不说我在 http://Repl.it 网站
谢谢!
推荐答案
sortWords [(str,num)] =
(上面的)函数定义模式匹配包含单个元素的列表,该元素是一个元组,具有两个值的变量.
Your function definition (above) pattern matches for a list containing a single element which is a tuple with variables for each of the two values.
您似乎只想要一个变量,而不想要任何模式匹配:
You seem to want just a variable and not a pattern match at all:
sortWords xs = sortBy (\x y -> compare (snd x) (snd y)) xs
或eta减少:
sortWords = sortBy (\x y -> compare (snd x) (snd y))
这篇关于如何修复Haskell中的“函数中的非穷举模式"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文