haskell - 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 xs
wherexs ="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
解决方案
该表达式fooHelp(x, read $ charToString( xs !! 0 ) :: Int)
试图将单个参数(一(Char, Int)
对)传递给fooHelp
,这是错误的。据推测,您想改为编写:
fooHelp (charToString x) (read $ charToString( xs !! 0 ) :: Int)
推荐阅读
- python - 无法使用 ModelViewSet 更改 Django 用户模型的用户密码
- amazon-web-services - Terraform 更新 Route53 域名称服务器
- string - 查找字符串在给定字符串中作为子序列出现的时间,带有通配符
- c - C fscanf 给出分段错误。说缺少文件(我的文件名为 lab4.dat 并且位于同一位置)
- swiftui - SwiftUI,UIScreen.main.bounds.midY 默认不居中
- azure-data-factory - 使用参数的 Azure 数据工厂数据流表达式生成器
- python - 'DataFrame' 对象没有属性 'map' 添加更多列
- bash - 使用特殊字符显示文件名
- java - 不确定为什么这个特定的测试用例不适用于合并二叉树
- r - 如何将 ggplot 的参数传递给重叠函数?