首页 > 解决方案 > haskell - 无法将类型“(Char,Int)”与“[Char]”错误匹配

问题描述

我正在编写一个函数来扩展一个字符串

例子:

foo "a4b4"

应该回馈:

"aaaabbbb"

这是我的代码:

foo :: String -> String
foo (x:xs) = let curent = fooHelp(x, read $ charToString( xs !! 0  ) :: Int)
             in x : (curent) ++ foo (tail xs)

foo帮助:

fooHelp :: String -> Int -> String
fooHelp x n 
             | n >= 3 = x ++ fooHelp x (n - 1) 
             | n == 2 = x
             | n == 1 = ""

和 charToString:

charToString :: Char -> String
charToString c = [c]

它需要 x 并将其附加到当前。在当前 fooHelp 将返回扩展字符串

示例:foo "a4b4"然后x = "a", xs = "4b4",xs !! 0 = '4' read $ charToString( xs !! 0 ) :: Int)将 char 转换'4'为 int4并将其与 x("a") -> 一起传递给 fooHelpfooHelp(x, 4)并返回 "aaa"。然后x : current应该回馈"aaaa"因为x = "a"和当前"aaa"然后递归调用++ foo tail xswherexs ="b4" 并且它应该重复该过程。

我收到错误消息:

test.hs:173:34: error:
    • Couldn't match type ‘(Char, Int)’ with ‘[Char]’
      Expected type: String
        Actual type: (Char, Int)
    • In the first argument of ‘fooHelp’, namely
        ‘(x, read $ charToString (xs !! 0) :: Int)’
      In the expression:
        fooHelp (x, read $ charToString (xs !! 0) :: Int)
      In an equation for ‘curent’:
          curent = fooHelp (x, read $ charToString (xs !! 0) :: Int)
    |
173 | foo (x:xs) = let curent = fooHelp(x, read $ charToString( xs !! 0  ) :: Int)
    |                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

我在哪里犯错了?我测试了函数 fooHelp,它可以很好地处理 foo 中的参数。

测试 fooHelp:

xs = "4b4"

test =  read $ charToString( xs !!0 ) :: Int

*Main> test
4

标签: haskellsyntaxsyntax-errortype-mismatchfunction-call

解决方案


该表达式fooHelp(x, read $ charToString( xs !! 0 ) :: Int)试图将单个参数(一(Char, Int)对)传递给fooHelp,这是错误的。据推测,您想改为编写:

fooHelp (charToString x) (read $ charToString( xs !! 0  ) :: Int)

推荐阅读