我正在尝试找到元素之和最小的列表。
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
为什么函数无法通过类型检查?
minimumBy (compare \
on` sum),并结合
Data.List和
Data.Function` 中的高阶函数。 - leftaroundabout1+2i
这样的复数就没有固定的排序方式。 - dflemstrshortest []
的值应该是什么,或者换句话说,递归的基础是什么(提示:通常对于空列表,minimum
和maximum
未定义)。 - Rafael Caetano