[英]list recursion in haskell
我有一份清单。 我需要创建一个新列表,如下例所示: [3, 3, 1, 3]
到[3, 3, 3, 1, 1, 3, 3]
。 任何人都可以告诉我的代码有什么问题吗?
add xs
= let
adding (x : xs) as
=
if x == head(xs) && length(xs) >= 1
then adding xs (x : as)
else adding xs (x : x : as)
adding _ as
= as
in
adding xs []
ghci告诉我总有空列表是xs
,但我有xs length
控制。
我不确定你最终要做什么,但我可以帮你避免“空列表”问题。
当列表(x:xs)
还有一个项目时, xs == []
。 (例如,如果(x:xs)
仅包含项1
,则x == 1
, xs == []
)。 在这种情况下, head xs
会导致异常,因为没有为空列表定义head
。
尝试更改线路
if x == head(xs) && length(xs) >= 1
至
if length(xs) >= 1 && x == head(xs)
在此更改之后,当xs == []
, length(xs) >= 1
计算结果为False
。 由于所有p
False && p == False
,Haskell跳过评估另一个表达式( x == head(xs)
),并避免异常。
尝试这个:
import Data.List
add xs = concat $ map (\(x:xs) -> x:x:xs) $ group xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.