Skip to content

Commit

Permalink
Merge pull request #13 from matthewleon/range
Browse files Browse the repository at this point in the history
range: unfold a range of values
  • Loading branch information
paf31 authored Dec 10, 2017
2 parents 40db258 + 2cf483d commit 101ce1c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Data/Unfoldable.purs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module Data.Unfoldable
, replicateA
, none
, singleton
, range
, fromMaybe
) where

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

-- | Create an Unfoldable containing a range of values, with both endpoints.
range :: forall f. Unfoldable f => Int -> Int -> f Int
range start end =
unfoldr (\i -> if i <= end then Just (Tuple i $ i + 1) else Nothing) start

-- | Convert a Maybe to any Unfoldable like lists and arrays.
fromMaybe :: forall f a. Unfoldable f => Maybe a -> f a
fromMaybe = unfoldr (\b -> flip Tuple Nothing <$> b)
5 changes: 5 additions & 0 deletions test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ main = do
[2,1,1],[2,1,2], [2,2,1],[2,2,2]
]

log "Test range"
assert $ U.range 1 0 == []
assert $ U.range 0 0 == [0]
assert $ U.range 0 2 == [0, 1, 2]

log "Test Maybe.toUnfoldable"
assert $ U.fromMaybe (Just "a") == ["a"]
assert $ U.fromMaybe (Nothing :: Maybe String) == []
Expand Down

0 comments on commit 101ce1c

Please sign in to comment.