Take the 2-minute tour ×

We have a standard input like:

1 2 3
4 5 6
1 3 2
5 3 2

Each line consists of exactly three numbers, for each line we'd like to compute the function value

f :: (Int, Int, Int) -> Int

and print the result. How to do that?

share|improve this question
This looks like a homework problem, which is kind of awesome. What have you tried so far? What do you think will be part of the solution? –  Jamey Sharp Nov 1 '12 at 22:55
@JameySharp No no, even if it definitely looks like that, I'm learning Haskell on my own :-) –  Cartesius00 Nov 2 '12 at 6:52
Fair enough! :-) –  Jamey Sharp Nov 2 '12 at 17:06

2 Answers 2

up vote 3 down vote accepted

I'll point out some useful functions that will aid you in your quest:

readFile :: FilePath -> IO String

lines :: String -> [String]

words :: String -> [String]

print :: (Show a) => a -> IO ()

I recommend you open up a ghci sessions, experiment with those functions a little bit and see what they do, and try to mix them together in creative ways. I'll give you a head start:

Prelude> str <- readFile "test.txt"
Prelude> print (length (lines str))
<The number of lines in the file "test.txt">
share|improve this answer
The other suggestion I'd add is that list comprehension syntax is very helpful for making this kind of task readable. It's especially convenient to use pattern matching: [...| [a,b,c] <- map words (lines str)]. Oh, and you'll need the read function. –  Jamey Sharp Nov 2 '12 at 17:14

A straightforward solution:

tuple3 :: [Int] -> (Int,Int,Int)
tuple3 [x,y,z] = (x,y,z)

main = mapM_ print . map (f . tuple3 . map read . words) . lines =<< getContents

I still don't understand why to use a tuple as the argument, it causes that ugly conversion.

share|improve this answer
And if f were f :: Int->Int->Int->Int? How would it change the main? –  Cartesius00 Nov 2 '12 at 6:56
@Martin it won't be neat anyway, but converting from a list to a tuple is ugly: it can't be guaranteed that the list has required amount of elements, the resulting tuple will be redundant (three equal types on end), so it is fraught with run-time exceptions. From aesthetic point of view, it's like comparing apples and oranges. Tuples and lists are objects of quite different type nature in Haskell (unlike Python): tuple is a fixed-size collection of items of any type (and I suspect it exists in compile-time only), list is a run-time sequence of items of the same type. –  EarlGray Nov 2 '12 at 10:12

Your Answer


