Skip to content

Commit 373cb37

Browse files
committed
Rewrote with accumulators to trigger tco.
Re: #5 (comment)
1 parent 065ad63 commit 373cb37

File tree

1 file changed

+13
-37
lines changed

1 file changed

+13
-37
lines changed

src/Data/Array.purs

Lines changed: 13 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -294,44 +294,20 @@ group xs = groupBy (==) xs
294294
group' :: forall a. (Ord a) => [a] -> [[a]]
295295
group' = group <<< sort
296296

297-
foreign import groupBy
298-
"function groupBy (eq) {\
299-
\ return function (arr) {\
300-
\ if (arr.length == 0) {\
301-
\ return [];\
302-
\ } else {\
303-
\ var res = [];\
304-
\ var spanned = {init: [], rest: arr.slice()};\
305-
\ while (true) {\
306-
\ var x = spanned.rest[0];\
307-
\ var xs = spanned.rest.slice(1);\
308-
\ spanned = span(eq(x))(xs);\
309-
\ spanned.init.unshift(x);\
310-
\ res.push(spanned.init);\
311-
\ if (spanned.rest.length == 0) {\
312-
\ break;\
313-
\ }\
314-
\ }\
315-
\ return res;\
316-
\ }\
317-
\ }\
318-
\}" :: forall a. (a -> a -> Boolean) -> [a] -> [[a]]
297+
groupBy :: forall a. (a -> a -> Boolean) -> [a] -> [[a]]
298+
groupBy = go []
299+
where
300+
go :: forall a. [[a]] -> (a -> a -> Boolean) -> [a] -> [[a]]
301+
go acc _ [] = reverse acc
302+
go acc op (x:xs) = let sp = span (op x) xs in
303+
go ((x:sp.init):acc) op sp.rest
319304

320-
foreign import span
321-
"function span (p) {\
322-
\ return function (arr) {\
323-
\ var res = {init: [], rest: []};\
324-
\ for (var i = 0, len = arr.length; i < len; i++) {\
325-
\ if (p(arr[i])) {\
326-
\ res.init.push(arr[i]);\
327-
\ } else {\
328-
\ res.rest = arr.slice(i);\
329-
\ break;\
330-
\ }\
331-
\ }\
332-
\ return res;\
333-
\ }\
334-
\}" :: forall a. (a -> Boolean) -> [a] -> { init :: [a], rest :: [a] }
305+
span :: forall a. (a -> Boolean) -> [a] -> { init :: [a], rest :: [a] }
306+
span = go []
307+
where
308+
go :: forall a. [a] -> (a -> Boolean) -> [a] -> { init :: [a], rest :: [a] }
309+
go acc p (x:xs) | p x = go (x:acc) p xs
310+
go acc _ xs = { init: reverse acc, rest: xs }
335311

336312
instance functorArray :: Functor [] where
337313
(<$>) = map

0 commit comments

Comments
 (0)