Skip to content

Commit 679d176

Browse files
committed
Merge pull request #5 from joneshf/master
Added group, groupBy and span.
2 parents c6a76b8 + 373cb37 commit 679d176

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@
4343

4444
findLastIndex :: forall a. (a -> Prim.Boolean) -> [a] -> Prim.Number
4545

46+
group :: forall a. (Eq a) => [a] -> [[a]]
47+
48+
group' :: forall a. (Ord a) => [a] -> [[a]]
49+
50+
groupBy :: forall a. (a -> a -> Prim.Boolean) -> [a] -> [[a]]
51+
4652
head :: forall a. [a] -> Maybe a
4753

4854
init :: forall a. [a] -> Maybe [a]
@@ -75,6 +81,8 @@
7581

7682
sortBy :: forall a. (a -> a -> Ordering) -> [a] -> [a]
7783

84+
span :: forall a. (a -> Prim.Boolean) -> [a] -> { rest :: [a], init :: [a] }
85+
7886
tail :: forall a. [a] -> Maybe [a]
7987

8088
take :: forall a. Prim.Number -> [a] -> [a]

src/Data/Array.purs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ module Data.Array
3030
, nubBy
3131
, sort
3232
, sortBy
33+
, group
34+
, group'
35+
, groupBy
36+
, span
3337
) where
3438

3539
import Data.Maybe
@@ -283,6 +287,28 @@ foreign import sortJS
283287
\ };\
284288
\}" :: forall a. (a -> a -> Number) -> [a] -> [a]
285289

290+
group :: forall a. (Eq a) => [a] -> [[a]]
291+
group xs = groupBy (==) xs
292+
293+
-- | Performs a sorting first.
294+
group' :: forall a. (Ord a) => [a] -> [[a]]
295+
group' = group <<< sort
296+
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
304+
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 }
311+
286312
instance functorArray :: Functor [] where
287313
(<$>) = map
288314

0 commit comments

Comments
 (0)