1
votes

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.

1
try writing out the types, it will help in the debugging a lot!jamshidh
Some hints: type String = [Char]. How will you read a line like 12 3 to get the answer 15? There must be something that does something with spaces. How will you convert a character like '7' into a number you can add like 7?Cirdec
interact 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, with readLn >>= flip replicateM getLine. The type of processInput must be [String] -> [String] but interact :: (String -> String) -> IO () - there are other type errors, but this is likely the source of the one you specifically mentioned.user2407038
fromDigits x and fromDigits xs one of these must be wrong. x is a Char while xs is a [Char] so the types do not match.Bakuriu

1 Answers

2
votes

Some hints, in order:

  • At some point, you need to convert your digits from Char to Int or the like.
    • Haskell won't do that for you unless you ask. Use ord.
  • In the x:xs pattern, xs is the rest of the list, not the next element.
    • This is likely where your [Char] vs. Char problem comes from.
  • It looks like you want to treat each line as a sequence of words.
    • Try using the words function.
  • Finally, you need to convert your numbers into printable form for output.
    • Haskell won't do that for you, either. Use show.

In general, I recommend starting up ghci and playing with it, just to gain some basic familiarity with Haskell. Pull up Hoogle or some other Haskell reference in another window...