Skip to content

Commit 3e7aa6d

Browse files
committed
add nats: natural numbers for lazy unfoldable
1 parent 40db258 commit 3e7aa6d

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
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 & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,16 @@ module Data.Unfoldable
1010
, replicateA
1111
, none
1212
, singleton
13+
, nats
1314
, fromMaybe
1415
) where
1516

1617
import Prelude
1718

19+
import Control.Lazy (class Lazy)
1820
import Data.Maybe (Maybe(..), isNothing, fromJust)
1921
import Data.Traversable (class Traversable, sequence)
2022
import Data.Tuple (Tuple(..), fst, snd)
21-
2223
import Partial.Unsafe (unsafePartial)
2324

2425
-- | This class identifies data structures which can be _unfolded_,
@@ -88,6 +89,15 @@ none = unfoldr (const Nothing) unit
8889
singleton :: forall f a. Unfoldable f => a -> f a
8990
singleton = replicate 1
9091

92+
-- | Produce a Lazy Unfoldable structure representing the natural numbers.
93+
--
94+
-- The result of this function is infinite.
95+
nats :: forall f a. Unfoldable f => Semiring a => Lazy (f a) => f a
96+
nats = unfoldr increment zero
97+
where
98+
increment :: a -> Maybe (Tuple a a)
99+
increment a = Just (Tuple a $ add one a)
100+
91101
-- | Convert a Maybe to any Unfoldable like lists and arrays.
92102
fromMaybe :: forall f a. Unfoldable f => Maybe a -> f a
93103
fromMaybe = unfoldr (\b -> flip Tuple Nothing <$> b)

0 commit comments

Comments
 (0)