如何在haskell中使用foldr實現插入。 我試過了:在haskell中使用foldr實現插入
insert'' :: Ord a => a -> [a] -> [a]
insert'' e xs = foldr (\x -> \y -> if x<y then x:y else y:x) [e] xs
沒有骰子。 我必須在列表中插入元素e,以便它在大於或等於它的第一個元素之前。
實施例:
insert'' 2.5 [1,2,3] => [1.0,2.0,2.5,3.0]
insert'' 2.5 [3,2,1] => [2.5,3.0,2.0,1.0]
insert'' 2 [1,2,1] => [1,2,2,1]
在最後一個例子中第一2插入一個。編輯: 謝謝@李。
我現在有這樣的:
insert'' :: Ord a => a -> [a] -> [a]
insert'' e xs = insert2 e (reverse xs)
insert2 e = reverse . snd . foldr (\i (done, l) -> if (done == False) && (vj e i) then (True, e:i:l) else (done, i:l)) (False, [])
where vj e i = e<=i
但是這是行不通的:
insert'' 2 [1,3,2,3,3] => [1,3,2,2,3,3]
insert'' 2 [1,3,3,4] => [1,3,2,3,4]
insert'' 2 [4,3,2,1] => [4,2,3,2,1]
SOLUTION:
insert'' :: Ord a => a -> [a] -> [a]
insert'' x xs = foldr pom poc xs False
where
pom y f je
| je || x > y = y : f je
| otherwise = x : y : f True
poc True = []
poc _ = [x]
感謝@Pedro羅德里格斯(它只是nedded改變X > = y到x> y)
(如何標記爲已回答?)
摺疊通常用於減少列表,而不是擴展它們。另外,你的描述和你的第三個例子是衝突的。根據你的描述,它應該插在3之前,就像你的第一個例子。 – bheklilr
對不起,我編輯了它。 – excrucio
@bheklilr:解決這個問題的最好方法是什麼?它是顯式遞歸還是有更高階的函數來解決這個問題? – Sibi