gpt4 book ai didi

haskell - 为什么递归案例不起作用?

转载 作者:行者123 更新时间:2023-12-02 17:07:20 25 4
gpt4 key购买 nike

我正在使用模式匹配编写一个 Haskell 函数,如下所示。

printLine :: [Int] -> [String]
printLine [] = error "Lege lijst levert niets op"
printLine [x] = "+" : replicate x "-"
printLine (x:xs) = ('+' : replicate x "-") : printLine xs

基本情况有效,但 GHC 在递归情况下给了我一个错误,如下所示:

Couldn't match expected type `Char' with actual type `[Char]'
In the second argument of `replicate', namely `"-"'
In the second argument of `(:)', namely `replicate x "-"'
In the first argument of `(:)', namely `('+' : replicate x "-")'

我做错了什么?请记住,我是 Haskell 和函数式编程的初学者。我希望有人能帮助我。

最佳答案

这里有两个错误。首先,注意单引号和双引号的区别:

'+' :: Char
"+" :: String

您希望在最后一行中写入 "+" 而不是 '+',因为您希望将 String 附加到replicate 返回的 String 列表。

其次,最后一行的外部 : 尝试连接 [String][String] (返回类型为 printLine),但其类型为 a -> [a] -> [a],因此它只需要一个 String 作为其第一个参数。您想在此处使用 (++) 来连接两个列表。此错误为您提供引用的错误消息。

更正后的代码为

printLine :: [Int] -> [String]
printLine [] = error "Lege lijst levert niets op"
printLine [x] = "+" : replicate x "-"
printLine (x:xs) = ("+" : replicate x "-") ++ printLine xs

关于haskell - 为什么递归案例不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19683699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com