【问题标题】:couldn't match expected type (Int -> Int -> Int) with actual type `(t0, t1, t2)'无法将预期类型 (Int -> Int -> Int) 与实际类型 `(t0, t1, t2)' 匹配
【发布时间】:2011-08-29 15:39:22
【问题描述】:

我是一名初学者,在进入大学学习计算机科学之前,我正在尝试做一些有关 Haskell 的教程。

我被这个程序卡住了。它需要三个数字并将它们按升序排列。谁能帮助我并告诉我出了什么问题,因为这让我发疯了?感谢您的宝贵时间。

import Prelude hiding (min,max)
orderTriple :: (Int -> Int -> Int) -> (Int -> Int -> Int)
max :: Int -> Int -> Int -> Int
min :: Int -> Int -> Int -> Int
middle :: Int -> Int -> Int -> Int


max x y z
 |(x>=y) && (x>=z)  = x
 |(y>=x) && (y>=z)  = y
 |otherwise     = z

min d e f
 |(d<=e) && (d<=f)  = d
 |(e<=d) && (e<=f)  = e
 |otherwise     = f

middle g h i
 | (g <= (max g h i)) && (g >= (min g h i)) = g
 | (h <= (max g h i)) && (h >= (min g h i)) = h
 | otherwise                    = i

orderTriple (a,b,c) = ((min a b c),(middle a b c),(max a b c))

错误是:

orderList.hs:23:13:
    Couldn't match expected type `[Int -> Int -> Int]'
                with actual type `(t0, t1, t2)'
    In the pattern: (a, b, c)
In an equation for `orderTriple':
    orderTriple (a, b, c) = [(min a b c), (middle a b c), (max a b c)]

【问题讨论】:

  • 你真的会在大学里做 Haskell(或某种 FP)吗?我希望我能在我的程序中得到它!

标签: haskell types tuples


【解决方案1】:

你给编译器错误的类型信息:

orderTriple :: (Int -> Int -> Int) -> (Int -> Int -> Int)

应该是

orderTriple :: (Int, Int, Int) -> (Int, Int, Int)

第一次输入声称orderTriple 将一个函数(从两个 Int 转换为一个)到另一个这样的函数,这根本不是您的代码所做的。

(另外:+1 用于学习 FP为 CS 课程做准备)。

【讨论】:

  • 非常感谢您的帮助,但这次又出现了另一个错误 :1:1: The function orderTriple' is applied to three arguments, but its type (Int, Int, Int) -> (Int, Int, Int)' 只有一个 在表达式中:orderTriple 3 1 9 在 `it' 的等式中:it = orderTriple 3 1 9
  • orderTriple 的定义需要一个元组,即括号中以逗号分隔的参数。你必须这样称呼它——orderTriples(3,1,9)——而不是用三个空格分隔(咖喱)不带括号的参数。
  • @noobie:您可能还想检查在orderTriple 的定义中使用的是圆括号() 而不是方括号[]。您给出的错误信息与上面列出的代码不同...
  • 是的,你又是对的!我调用了不带括号的函数:orderTriple 3 1 9,这就是它出现此错误的原因!感谢您的帮助:)祝您有美好的一天
【解决方案2】:

箭头-&gt; 分隔函数的参数。 (实际上稍微复杂一点)但是要分隔元组的参数,请使用逗号:

orderTriple :: (Int,Int,Int) -> (Int,Int,Int)

如果是其他类型,空格就足够了:

Either String Int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 2012-08-29
    • 2019-04-23
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多