Jump to content

Haskell triples and lists

- - - - -

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

#1
cordedconch

cordedconch

    Newbie

  • Members
  • Pip
  • 3 posts
Hi everyone–

Say I have a list of triples with the type:
[(Int, [Int], Int)]

so for example the user may input:

[(1, [1,2,3,4], 8)]
[(4, [2,4], 19)]
[(3, [1,5,9,10], 10)]
[(23, [9,9,2,27,1], 1)]
[(5, [1,4,2,6,8,4], 7)]

I am trying to write a program in Haskell that goes through all of the user inputted triples and returns a single integer. I want this integer to be the length of the longest list out of all the triples. In the example above, the longest list is in the 5th line, and it is 6 integers long. So the integer should be 6.

The program should be able to cope with as many triples as the user chooses to input.

I have gotten thus far:

Here is the type definition for my main function:
biggest :: [(Int, [Int], Int)] -> a

Here is my function that singles out the middle element in the triple (this is the only part of the triple that we’re concerned about):
center :: (a, [Int], c) -> [Int]
center (_, [x] ,_) = [x]

Here is my function that determines the length of the middle element:
length’ :: [a] -> Int
length’ [] = 0
length’ (_:l) = 1 + len l

I’m trying to work out a way to stitch it all together, but am having some difficulty. Any suggestions?

Thank you !

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Well, first you don't need to write a length' function, Haskell already comes with that. :) What you'll want to write is a really simple function that just finds the longest list in the triples, which I did by using foldl:

biggest :: [(Int, [Int], Int)] -> [Int]
biggest = foldl (\v (_, x, _) -> if length x > length v then x else v) []

However, for the sake of genericism, I'd write a function that just returns the longest of two lists:

longest :: [a] -> [a] -> [a]
longest l1 l2 = if length l1 > length l2 then l1 else l2

Then write the method that foldl's using that:

biggest :: [(a, [b], c)] -> [b]
biggest = foldl (\v (_, x, _) -> longest v x) []

Then you could just do this for your main method:

main = getInput >>= interpretInput >>= (putStrLn $ biggest)

That should do it. If you need help parsing user input, I'll help, but I'll leave that for you for now.
Wow I changed my sig!