Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading input from stdin in haskell and converting to list of integers

Tags:

haskell

What is wrong with the following code? I just wanted to connvert input in the following format in a file: n - count of test cases // n numbers n1 n2 (read via stdin) into list of integers and display it?

socks :: Int -> Int
socks x = x + 1
strToInt = read :: String -> Int
strLToIntL :: [String] -> [Int]
strLToIntL xs = map (strToInt) xs
main = do
    n <- readLn :: IO Int
    mapM_ putStrLn $ map show $ strLToIntL $ fmap (take n . lines) getContents

I am getting the compile error when i run it:

Couldn't match expected type `Char' with actual type `[Char]'
Expected type: String -> [Char]
  Actual type: String -> [String]
In the second argument of `(.)', namely `lines'
In the first argument of `fmap', namely `(take n . lines)'
like image 338
thayumanavar Avatar asked Dec 24 '13 05:12

thayumanavar


1 Answers

The problem is that

getContents :: IO String

so

fmap (take n . lines) getContents :: IO [String]

This can't be fed to something expecting a [String]. To fix this you need to "bind" the IO action. Using do notation you could write this as

main = do
  n <- readLine :: IO Int
  input <- fmap (take n . lines) getContents
  mapM_ putStrLn . map show . strLToIntL $ input

You could change that last line to just

 mapM print . strLToIntL $ input
like image 153
Daniel Gratzer Avatar answered Nov 13 '22 15:11

Daniel Gratzer