[英]lastList function in a list without calling a Prelude in Haskell
我有此函数lastList,它假定要调用列表的最后一个元素。 我需要手动执行,而Prelude中没有预定义的“ last”。 到目前为止我有这段代码
lastList :: List a -> a
lastList list = case list of
Empty -> error "List is empty"
Cons _ xs -> lastList xs
它给我一个带有列表的输出“列表为空”
test3 :: List Double
test3 = Cons 1.3 (Cons 5.2 (Cons 3.0 (Cons 8.7 (Cons 9.1 Empty))))
问题是什么? 谢谢
问题 :您只将Empty
定义为基本情况,这会出错。 因此,每个非无限列表最终都会导致Empty
basecase和错误。 无限列表将永远循环,但这是我们不能回避的事情,因为无限列表根本没有最后一个元素。
由于List
是一个链表,具有一个head
(这是一个元素)和一个tail
(这是列表的其余部分)作为Cons head tail
和一个Empty
,因此具有一个元素的列表就是Cons x Empty
。 因此,这意味着万一我们获得了这种模式,我们应该返回x
。
此外,如果tail
不为Empty
,则应该对尾部执行递归,直到获得仅剩一个元素的列表。
如果列表为Empty
,则列表为空,因此我们应该在此输入上出错。
lastList :: List a -> a
lastList Empty = error "List is empty"
lastList (Cons x Empty) = x
lastList (Cons _ xs) = lastList xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.