Haskell'无法与实际类型匹配预期类型'
我一直在阅读七周中的七种语言书籍,并正在与Haskell合作。Haskell'无法与实际类型匹配预期类型'
我的问题挣扎:
写那种需要一个列表和比较它的两个参数,然后返回一个排序列表的功能。
我在网上寻找帮助,发现了一个解决方案,但我甚至无法得到解决方案,因为预计会出现实际的类型错误。
这是我一直在试图代码:
module Main where
import Data.List
sortList :: (Ord a) => (a -> a -> Ordering) -> [a] -> [a]
sortList comparator list = sortBy comparator list
以下是错误:
*Main> sortList [5,4,2,7,8,1]
<interactive>:1:10:
Couldn't match expected type `a -> a -> Ordering'
with actual type `[t]'
In the first argument of `sortList', namely `[5, 4, 2, 7, ....]'
In the expression: sortList [5, 4, 2, 7, ....]
In an equation for `it': it = sortList [5, 4, 2, ....]
我的思考和尝试:
也许我我打电话功能错了吗?我对Haskell相当陌生。 II也尝试了许多搜索。我所能得出的结论是某处的类型不匹配。我想对剧本的解释和指导对我很有帮助。
你的函数签名说:
"sortList is a function that takes:"
- function (a -> a -> Ordering) that take two elements of type 'a' and returns an 'Ordering' [this is your comparator]
- List of items 'a' ([a]) that you are passing it
- Returns a list of items 'a' ([a])
试着打电话给他们以这样的方式
sortList compare [3,2,1]
更多阅读这里: https://hackage.haskell.org/package/base-4.8.2.0/docs/Data-Ord.html
这里: http://zvon.org/other/haskell/Outputprelude/compare_f.html
工作。你能简要解释一下为什么? – Justin
你看过我的评论吗?你需要将比较器方法传递给你的函数。 '比较'是你需要的比较器。 欲了解更多信息,请访问:http://zvon.org/other/haskell/Outputprelude/compare_f.html and here: https://hackage.haskell.org/package/base-4.8.2.0/docs/Data -Ord.html – granmirupa
您正在调用错误的函数,您需要将它传递给比较函数。您只需将一个列表传递给该函数。
好你的签名alrea dy说:调用'sortList'需要一个你没有提供的'比较器'... –