简体   繁体   中英

Haskell : Transform String -> [List]

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM