[英]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.