max' :: Int -> Int -> Int
max' a b = if a >= b then a else b
你看到这个函数是正确的,但如果我写
let a = 3,
let b = 3
还有如果我写
ghci> a == b => True
所以它比较它们那么为什么它不在我的函数中进行比较
ghci> max' a b
为什么会出现错误?或者写它的正确方法是什么?
对不起,我是初学者,如果我的问题很愚蠢,请原谅我,如果需要,请编辑它,谢谢
<interactive>:19:6:
Couldn't match expected type `Int' with actual type `Integer'
In the first argument of max', namely `a'
In the expression: max' a b
In an equation for `it': it = max' a b
<interactive>:19:8:
Couldn't match expected type `Int' with actual type `Integer'
In the second argument of max', namely `b'
In the expression: max' a b
In an equation for `it': it = max' a b
最佳答案
我猜你是在 ghci
解释器中这样做的。然后,看看( :t
显示表达式的类型, a :: t
形式的一行表示 a
的类型为 t
):
Prelude> let a = 3
Prelude> :t a
a :: Integer
ghci
解释器提前提交并为 a
提供 Integer
类型,尽管它应该提供任何数字类型(因此 a :: Num t => t
)。现在,您的函数接收
Int
s 作为参数,但由于 a
和 b
是 Integer
s,您会收到该错误消息。您可以删除限制性类型签名,也可以将
a
和 b
定义为 Int
。我会选择第一个选项,除非有一些要求使用 Int
-only 类型签名。为此,您需要在定义的末尾添加 ::Int
:Prelude> let b = 42 :: Int
Prelude> :t b
b :: Int
如果您想删除签名,请将您的函数重新编码为只有一行:
max' a b = if a >= b then a else b
现在,如果你要检查它的类型:
Prelude> :t max'
max' :: Ord a => a -> a -> a
这意味着您有一个通用函数,它适用于可以订购的任何类型。
另一种 是使用扩展名
ghci
启动 ghci -XNoMonomorphismRestriction
。在这种情况下:Prelude> let a = 3
Prelude> :t a
a :: Num a => a
这将直接适用于您的功能。
没有这个扩展的
ghci
提交Integer
的原因是Monomorphism restriction
关于haskell - 编写 max 函数时输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20036701/