Skip to content

range: unfold a range of values #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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