Skip to content

Commit 101ce1c

Browse files
authored
Merge pull request #13 from matthewleon/range
range: unfold a range of values
2 parents 40db258 + 2cf483d commit 101ce1c

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

src/Data/Unfoldable.purs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ module Data.Unfoldable
1010
, replicateA
1111
, none
1212
, singleton
13+
, range
1314
, fromMaybe
1415
) where
1516

@@ -88,6 +89,11 @@ none = unfoldr (const Nothing) unit
8889
singleton :: forall f a. Unfoldable f => a -> f a
8990
singleton = replicate 1
9091

92+
-- | Create an Unfoldable containing a range of values, with both endpoints.
93+
range :: forall f. Unfoldable f => Int -> Int -> f Int
94+
range start end =
95+
unfoldr (\i -> if i <= end then Just (Tuple i $ i + 1) else Nothing) start
96+
9197
-- | Convert a Maybe to any Unfoldable like lists and arrays.
9298
fromMaybe :: forall f a. Unfoldable f => Maybe a -> f a
9399
fromMaybe = unfoldr (\b -> flip Tuple Nothing <$> b)

test/Main.purs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ main = do
4242
[2,1,1],[2,1,2], [2,2,1],[2,2,2]
4343
]
4444

45+
log "Test range"
46+
assert $ U.range 1 0 == []
47+
assert $ U.range 0 0 == [0]
48+
assert $ U.range 0 2 == [0, 1, 2]
49+
4550
log "Test Maybe.toUnfoldable"
4651
assert $ U.fromMaybe (Just "a") == ["a"]
4752
assert $ U.fromMaybe (Nothing :: Maybe String) == []

0 commit comments

Comments
 (0)