gpt4 book ai didi

haskell - 为什么我会收到无法推断 (Ord a) 错误?

转载 作者:行者123 更新时间:2023-12-03 15:10:17 26 4
gpt4 key购买 nike

我试图找到元素总和最小的列表。:

shortest :: (Num a) => [[a]] -> [a]
shortest [] = []
shortest (x:xs) = if sum x < sum (shortest xs) then x else shortest xs

这给了我以下错误:

Could not deduce (Ord a) arising from a use of `<'
from the context (Eq a)
bound by the type signature for shortest :: Eq a => [[a]] -> [a]
at code.hs:(8,1)-(9,71)
Possible fix:
add (Ord a) to the context of
the type signature for shortest :: Eq a => [[a]] -> [a]
In the expression: sum x < sum (shortest xs)
In the expression:
if sum x < sum (shortest xs) then x else shortest xs
In an equation for `shortest':
shortest (x : xs)
= if sum x < sum (shortest xs) then x else shortest xs


为什么函数不进行类型检查?

最佳答案

该代码涉及两个类型类:NumOrd .笔记
一个类型可以是成员Num而不是 Ord ,反之亦然。
sum的类型是 Num a => [a] -> a所以输入元素到shortest需要成为 Num 的成员.您还可以执行以下操作
在您的代码中:

sum x < sum (shortest xs)

这意味着您正在使用运算符 <a s,但在您的类型签名中,您没有要求 a s 是 Ord 的一个实例它定义了 < :
class Eq a => Ord a where
compare :: a -> a -> Ordering
(<) :: a -> a -> Bool
...

因此,您需要将该要求添加到您的类型签名中:
shortest :: (Ord a, Num a) => [[a]] -> [a]

或者你可以省略类型签名。

关于haskell - 为什么我会收到无法推断 (Ord a) 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13003150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com