diff --git a/src/Data/Unfoldable.purs b/src/Data/Unfoldable.purs index b3b034f..72b1baa 100644 --- a/src/Data/Unfoldable.purs +++ b/src/Data/Unfoldable.purs @@ -10,6 +10,7 @@ module Data.Unfoldable , replicateA , none , singleton + , range , fromMaybe ) where @@ -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) diff --git a/test/Main.purs b/test/Main.purs index 515a546..897c71b 100644 --- a/test/Main.purs +++ b/test/Main.purs @@ -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) == []