简体   繁体   English

Haskell:转换字符串-> [列表]

[英]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 : 我正在尝试在第一行中读取n,然后读取n行输入,并从每行打印前2个元素的总和,例如:

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' 无法将类型'[Char]'与'Char'匹配

Couldn't match type 'Char' with '[String]' 无法将类型'Char'与'[String]'相匹配

I am new to Haskell so I am unsure how to solve it. 我是Haskell的新手,所以不确定如何解决它。

Some hints, in order: 一些提示,顺序为:

  • At some point, you need to convert your digits from Char to Int or the like. 在某些时候,您需要将数字从Char转换为Int等。
    • Haskell won't do that for you unless you ask. 除非您提出要求,Haskell不会为您这样做。 Use ord . 使用ord
  • In the x:xs pattern, xs is the rest of the list, not the next element. x:xs模式中, xs是列表的其余部分,而不是下一个元素。
    • This is likely where your [Char] vs. Char problem comes from. 这可能是您的[Char]相对于Char问题的来源。
  • It looks like you want to treat each line as a sequence of words. 看起来您想将每行视为一个单词序列。
    • Try using the words function. 尝试使用words功能。
  • Finally, you need to convert your numbers into printable form for output. 最后,您需要将数字转换成可打印的形式以输出。
    • Haskell won't do that for you, either. Haskell也不会为您这样做。 Use show . 使用show

In general, I recommend starting up ghci and playing with it, just to gain some basic familiarity with Haskell. 通常,我建议启动ghci并使用它,以使您对Haskell有一些基本的了解。 Pull up Hoogle or some other Haskell reference in another window... 在另一个窗口中拉起Hoogle或其他Haskell参考...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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