我是 Haskell 的一个完整的初学者。我有一个在 Haskell 中使用的元组列表:结构是这样的[(a,b),(c,d),(e,f),(g,h)]
我想要的是根据第二个值返回这个元组中的最大元素:所以如果元组列表是[(4,8),(9,10),(15,16),(10,4)]
,我希望最大元素是(15,16)
。
但我不知道该怎么做。这是我迄今为止的尝试,
maximum' :: (Ord a) => (Num a) => [(a,b)] -> a
maximum' [] = error "maximum of empty list"
maximum' [(x,y)] = -1
maximum' (x:xs)
| snd x > snd(xs !! maxTail) = 0
| otherwise = maxTail
where maxTail = maximum' xs + 1
我收到这条错误消息,这对我来说毫无意义:
newjo.hs:23:25:
Could not deduce (a ~ Int)
from the context (Ord a, Num a)
bound by the type signature for
maximum' :: (Ord a, Num a) => [(a, b)] -> a
at newjo.hs:19:14-47
`a' is a rigid type variable bound by
the type signature for maximum' :: (Ord a, Num a) => [(a, b)] -> a
at newjo.hs:19:14
In the second argument of `(!!)', namely `maxTail'
In the first argument of `snd', namely `(xs !! maxTail)'
In the second argument of `(>)', namely `snd (xs !! maxTail)'`
我需要一些关于如何做到这一点的帮助。