【发布时间】:2018-08-28 04:11:08
【问题描述】:
我是 Haskell 编程的新手,我正在尝试创建一个递归函数“金字塔”,它返回如下字符串:
金字塔 0 ==> “0”
金字塔 1 ==> "0,1,0"
金字塔 2 ==> "0,1,2,1,0"
金字塔 3 ==> "0,1,2,3,2,1,0"
--更新--
pyramidHelper :: Integer -> String
pyramidHelper n | n == 0 = ['0']
| otherwise = pyramidHelper (n-1) ++ [','] ++ ['n'] ++ [','] ++ pyramidHelper (n-1)
pyramid :: Integer -> String
pyramid n | n == 0 = show 0
| otherwise = pyramidHelper n
我收到异常:'Prelude.read: no parse'。我阅读了Haskell Prelude.read: no parse String 并尝试更改代码,但没有成功。
【问题讨论】:
-
我发现首先使用字符串而不是整数列表很奇怪。通过使用字符串,您基本上会“丢失信息”。
-
@WillemVanOnsem 这是一个练习,我稍后会学习列表,所以这就是我必须使用字符串的原因。 :)
-
字符串是列表,这就是为什么你可以在它们上使用
(++) :: [a] -> [a] -> [a]。"0,1,0"只是['0', ',', '1', ',', '0']的语法糖。 -
@chepner 好的,非常感谢! :)
-
你没有在任何地方打电话给
read,所以很难看出你是如何从中得到错误消息的。
标签: string haskell recursion numbers