Skip to content

Commit 0054809

Browse files
committed
add nats: natural numbers for lazy unfoldable
1 parent 101ce1c commit 0054809

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
@@ -11,15 +11,16 @@ module Data.Unfoldable
1111
, none
1212
, singleton
1313
, range
14+
, nats
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)
22-
2324
import Partial.Unsafe (unsafePartial)
2425

2526
-- | This class identifies data structures which can be _unfolded_,
@@ -94,6 +95,15 @@ range :: forall f. Unfoldable f => Int -> Int -> f Int
9495
range start end =
9596
unfoldr (\i -> if i <= end then Just (Tuple i $ i + 1) else Nothing) start
9697

98+
-- | Produce a Lazy Unfoldable structure representing the natural numbers.
99+
--
100+
-- The result of this function is infinite.
101+
nats :: forall f a. Unfoldable f => Semiring a => Lazy (f a) => f a
102+
nats = unfoldr increment zero
103+
where
104+
increment :: a -> Maybe (Tuple a a)
105+
increment a = Just (Tuple a $ add one a)
106+
97107
-- | Convert a Maybe to any Unfoldable like lists and arrays.
98108
fromMaybe :: forall f a. Unfoldable f => Maybe a -> f a
99109
fromMaybe = unfoldr (\b -> flip Tuple Nothing <$> b)

0 commit comments

Comments
 (0)