I am trying to read n on the first line then n lines of input and print the sum of the first 2 elements from each line such as :
Input:
2
1 2
3 4
Output:
3
7
so far my code looks like:
import Control.Monad
fromDigits = foldl addDigit 0
where addDigit num d = 10*num + d
first (x:xs) = fromDigits x
second (x:xs) = fromDigits xs
main = interact processInput
processInput input = unlines [perLine line | line <- lines input]
perLine line = first line + second line
but I get the following error
Couldn't match type '[Char]' with 'Char'
Couldn't match type 'Char' with '[String]'
I am new to Haskell so I am unsure how to solve it.
type String = [Char]
. How will you read a line like12 3
to get the answer15
? There must be something that does something with spaces. How will you convert a character like'7'
into a number you can add like7
? – Cirdecinteract
only deals with one line at a time, and never stops. You should read the first line, then precisely the number of lines specified by that first line - for example, withreadLn >>= flip replicateM getLine
. The type ofprocessInput
must be[String] -> [String]
butinteract :: (String -> String) -> IO ()
- there are other type errors, but this is likely the source of the one you specifically mentioned. – user2407038fromDigits x
andfromDigits xs
one of these must be wrong.x
is aChar
whilexs
is a[Char]
so the types do not match. – Bakuriu