1

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.

4
  • 4
    try writing out the types, it will help in the debugging a lot! Commented Mar 3, 2016 at 16:59
  • 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? Commented Mar 3, 2016 at 17:12
  • 1
    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. Commented Mar 3, 2016 at 17:16
  • 2
    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. Commented Mar 3, 2016 at 17:25

1 Answer 1

2

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.