haskell - Finding maximum element in a list of tuples -
i complete beginner in haskell. have list of tuples i'm using in haskell: structure [(a,b),(c,d),(e,f),(g,h)]
what want return maximum element in tuple according second value: if list of tuples [(4,8),(9,10),(15,16),(10,4)]
, want maximum element (15,16)
.
but have no idea how this. attempt far,
maximum' :: (ord a) => (num a) => [(a,b)] -> maximum' [] = error "maximum of empty list" maximum' [(x,y)] = -1 maximum' (x:xs) | snd x > snd(xs !! maxtail) = 0 | otherwise = maxtail maxtail = maximum' xs + 1
and error message makes no sense me:
newjo.hs:23:25: not deduce (a ~ int) context (ord a, num a) bound type signature maximum' :: (ord a, num a) => [(a, b)] -> @ newjo.hs:19:14-47 `a' rigid type variable bound type signature maximum' :: (ord a, num a) => [(a, b)] -> @ newjo.hs:19:14 in second argument of `(!!)', namely `maxtail' in first argument of `snd', namely `(xs !! maxtail)' in second argument of `(>)', namely `snd (xs !! maxtail)'`
i need on how this.
the solutions presented far have been elegant, , should use them in real code write. here's version uses same pattern-matching style you're using.
maximum' :: ord => [(t, a)] -> (t, a) maximum' [] = error "maximum of empty list" maximum' (x:xs) = maxtail x xs maxtail currentmax [] = currentmax maxtail (m, n) (p:ps) | n < (snd p) = maxtail p ps | otherwise = maxtail (m, n) ps
this solution avoids juggling indices around, , instead keeps track of current maximum element, returned when entire list has been traversed. avoiding indices lists considered practice.
Comments
Post a Comment