Jump to content

Lists of Tuples in Haskell

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
markyp

markyp

    Newbie

  • Members
  • Pip
  • 2 posts
Well, I'm pretty new to Haskell and what i basically want to do is this:
I have a list of tuples (they are type Int is that is important):
[((a,b),c),...,((x,y),z)]
i want to find the maximum of the c part and then return the (a,b) part corresponding to that.
I have tried to go like:
maximum (map snd [list])
This will give me the maximum of the second part but how do i then get the first part back again?

Any help would be awesome! :)

Mark

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Go through each element in the list using foldl, and compare each second element. Then return the first one that is of the largest second element. Here's how I'd do it:

goThroughList :: [((Int, Int), Int)] -> (Int, Int)
goThroughList = foldl (\x y -> if snd x > snd y then fst x else fst y) ((0, 0), minIntValue)

foldl is extremely useful for going through lists and selecting one element out of many. For example, this is similar to how you'd get the largest element in a list.
I hope this was at least somewhat useful. :)
Wow I changed my sig!

#3
markyp

markyp

    Newbie

  • Members
  • Pip
  • 2 posts
Thanks a lot Zeke.