任务: “定义一个函数‘start’,返回给定列表中除最后一个之外的所有元素”
我的解决方案:
start list = start' list []
where
start' (x:[]) acc = acc
start' (x:xs) acc = start' xs (acc:x)
尝试编译时,ghc 似乎会抛出错误,因为第 4 行的最后一个表达式位于“(acc:x)”。 有人可以解释一下这是为什么吗? 我真的不在乎这是否是解决这个问题的最有效方法 - 我只是想知道我错在哪里。
非常感谢。
最佳答案
(acc:x)
没有多大意义:acc
是一个列表,x
是一个元素。 (:)::a -> [a] -> [a]
接受一个项目和一个列表,并构造一个列表,其中该项目是第一个项目,给定的列表是剩余的列表结果中的项目。
您可以在右端附加:
start list = start' list []
where
start' (x : []) acc = acc
start' (x : xs) acc = start' xs (acc ++ [x])
你的start
在这里基本上做了什么init :: [a] -> [a]
确实如此,只不过您的 start
版本也适用于空列表。
然而,使用累加器并不是必需的,只会增加计算量和内存使用量。您可以使用:
start :: [a] -> [a]
start [] = []
start (x : xs) = go xs x
where
go [] _ = []
go (x : xs) y = <b>y :</b> go xs x
或更短:
start :: [a] -> [a]
start [] = []
start (x : xs) = go xs x
where
go [] = <b>const []</b>
go (x : xs) = <b>(:</b> go xs x<b>)</b>
这也允许使用无限列表,其中开始
永远不会停止,但只需要有限的内存。
关于list - Haskell:我似乎无法在以下递归函数中将任何内容链接到我的累加器 - 谁能解释我在这里错在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76552439/