【问题标题】:Haskell 'Couldn't match expected type with actual type'Haskell'无法将预期类型与实际类型匹配'
【发布时间】:2016-04-23 14:44:06
【问题描述】:

我一直在阅读《七周内的七种语言》一书,我正在使用 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 相当陌生。我也尝试了很多搜索。我所能得出的结论是,某处类型不匹配。我想脚本的解释和指导对我很有帮助。

【问题讨论】:

  • 你的签名已经说明了:调用sortList 需要comparator 你没有提供...

标签: haskell types ghci


【解决方案1】:

你的函数签名说:

"sortList 是一个函数,它接受:"

  • 函数(a -> a -> Ordering)采用两个“a”类型的元素并返回一个“Ordering”[这是您的比较器]
  • 您正在传递的项目“a”([a]) 列表
  • 返回项目 '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

【讨论】:

【解决方案2】:

你调用了错误的函数,你需要传递一个比较器函数。您只需将列表传递给函数。

【讨论】:

    猜你喜欢
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多