on master help sign in
Have partition, unzip, intersperse use constant stack space
commit6e4bcf0e87dc0e825e3f9b0691147f55285ef958 authorMax New <maxsnew@gmail.com> dateThu 24 Apr 2014, 17:20 (13 years ago) parent4cf9383
2 files changed+16−18
libraries/List.elm+14−16 tests/elm/Test/List.elm+2−2
libraries/List.elm+14−16
@@ -170,13 +170,12 @@ not.
170170 partition (\x -> x < 3) [0..5] == ([0,1,2], [3,4,5])
171171 partition isEven [0..5] == ([0,2,4], [1,3,5])
172172-}
173−-- | TODO: foldify
174173partition : (a -> Bool) -> [a] -> ([a],[a])
175−partition pred lst =
176− case lst of
177− [] -> ([],[])
178− x::xs -> let (bs,cs) = partition pred xs in
179− if pred x then (x::bs,cs) else (bs,x::cs)
174+partition pred =
175+ let step x (ts, fs) = if pred x
176+ then (x::ts, fs)
177+ else (ts, x::fs)
178+ in foldr step ([],[])
180179
181180{-| Combine two lists, combining them into tuples pairwise.
182181If one list is longer, the extra elements are dropped.
@@ -198,12 +197,10 @@ zipWith = Native.List.zipWith
198197{-| Decompose a list of tuples.
199198 unzip [(0, True), (17, False), (1337, True)] == ([0,17,1337], [True,False,True])
200199-}
201−-- | TODO: foldify
202200unzip : [(a,b)] -> ([a],[b])
203−unzip pairs =
204− case pairs of
205− [] -> ([],[])
206− (x,y)::ps -> let (xs,ys) = (unzip ps) in (x::xs,y::ys)
201+unzip =
202+ let step (x,y) (xs, ys) = (x::xs, y::ys)
203+ in foldr step ([], [])
207204
208205{-| Places the given value between all of the lists in the second
209206argument and concatenates the result.
@@ -217,13 +214,14 @@ join = Native.List.join
217214
218215 intersperse "on" ["turtles","turtles","turtles"] == ["turtles","on","turtles","on","turtles"]
219216-}
220−-- | TODO: foldify
221217intersperse : a -> [a] -> [a]
222218intersperse sep xs =
223− case xs of
224− a::b::cs -> a :: sep :: intersperse sep (b::cs)
225− [a] -> [a]
226− [] -> []
219+ case xs of
220+ [] -> []
221+ hd::tl ->
222+ let step x rest = sep :: x :: rest
223+ spersed = foldr step [] tl
224+ in hd :: spersed
227225
228226{-| Take the first n members of a list: `(take 2 [1,2,3,4] == [1,2])` -}
229227take : Int -> [a] -> [a]
tests/elm/Test/List.elm+2−2
@@ -22,14 +22,14 @@ tests =
2222 ]
2323 unzipTests = [
2424 test "unzip doc check" <| assertEqual ([0,17,1337],[True,False,True]) (unzip [(0, True), (17, False), (1337, True)]),
25− let n = 1000000
25+ let n = 100000
2626 ts = repeat n True
2727 fs = repeat n False
2828 in test "unzip stress test" <| assertEqual (ts, fs) (unzip (zip ts fs))
2929 ]
3030 intersperseTests = [
3131 test "intersperse doc check" <| assertEqual ["turtles","on","turtles","on","turtles"] (intersperse "on" ["turtles","turtles","turtles"]),
32− let n = 1000000
32+ let n = 100000
3333 ts = repeat n True
3434 fs = repeat n False
3535 in test "intersperse stress test" <| assertEqual (tail . List.concat <| zipWith (\x y -> [x,y]) fs ts)