Skip to content

Commit e23562b

Browse files
committed
Unfoldable.iterate
1 parent 101ce1c commit e23562b

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

bower.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
],
1919
"dependencies": {
2020
"purescript-partial": "^1.2.0",
21-
"purescript-tuples": "^4.0.0"
21+
"purescript-tuples": "^4.0.0",
22+
"purescript-control": "^3.3.1"
2223
},
2324
"devDependencies": {
2425
"purescript-assert": "^3.0.0",

src/Data/Unfoldable.purs

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

1718
import Prelude
1819

20+
import Control.Lazy (class Lazy)
1921
import Data.Maybe (Maybe(..), isNothing, fromJust)
2022
import Data.Traversable (class Traversable, sequence)
2123
import Data.Tuple (Tuple(..), fst, snd)
@@ -89,6 +91,15 @@ none = unfoldr (const Nothing) unit
8991
singleton :: forall f a. Unfoldable f => a -> f a
9092
singleton = replicate 1
9193

94+
-- | Lazily produce an Unfoldable structure by iterating a function.
95+
-- | For example, to lazily produce integers starting with zero:
96+
-- |
97+
-- | ~~~ purescript
98+
-- | nats = iterate add zero
99+
-- | ~~~
100+
iterate :: forall f a. Unfoldable f => Lazy (f a) => (a -> a) -> a -> f a
101+
iterate f = unfoldr (\x -> Just (Tuple x (f x)))
102+
92103
-- | Create an Unfoldable containing a range of values, with both endpoints.
93104
range :: forall f. Unfoldable f => Int -> Int -> f Int
94105
range start end =

0 commit comments

Comments
 (0)