我正在尝试创建一个以元组列表作为参数的函数.该函数通过每个元组的第二个元素对元组列表进行排序.我的代码是创建一个模式,它匹配元组列表只有一个元素.为了测试,我调用带有两个元素的元组列表的函数,并且我有'函数中的非穷举模式'错误.
如何创建模式以匹配元组列表中的所有元素.
这是创建函数的代码.
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 pairs = sortBy (\x y -> compare (snd x) (snd y)) pairs
Run Code Online (Sandbox Code Playgroud)
这可以进一步减少η:
sortWords = sortBy (\x y -> compare (snd x) (snd y))
Run Code Online (Sandbox Code Playgroud)
模式匹配将使得在内部拉姆达感,但:
sortWords = sortBy (\(_,x) (_,y) -> compare x y)
Run Code Online (Sandbox Code Playgroud)
有标准的辅助函数使它更简单:
import Data.Ord (comparing)
sortWords = sortBy $ comparing snd
Run Code Online (Sandbox Code Playgroud)