Skip to content

add nats: natural numbers for lazy unfoldable #12

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

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 2 additions & 1 deletion bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
],
"dependencies": {
"purescript-partial": "^1.2.0",
"purescript-tuples": "^4.0.0"
"purescript-tuples": "^4.0.0",
"purescript-control": "^3.3.1"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for this any more, right?

},
"devDependencies": {
"purescript-assert": "^3.0.0",
Expand Down
12 changes: 11 additions & 1 deletion src/Data/Unfoldable.purs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ module Data.Unfoldable
, none
, singleton
, range
, nats
, fromMaybe
) where

import Prelude

import Control.Lazy (class Lazy)
import Data.Maybe (Maybe(..), isNothing, fromJust)
import Data.Traversable (class Traversable, sequence)
import Data.Tuple (Tuple(..), fst, snd)

import Partial.Unsafe (unsafePartial)

-- | This class identifies data structures which can be _unfolded_,
Expand Down Expand Up @@ -94,6 +95,15 @@ 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

-- | Produce a Lazy Unfoldable structure representing the natural numbers.
--
-- The result of this function is infinite.
nats :: forall f a. Unfoldable f => Semiring a => Lazy (f a) => f a
nats = unfoldr increment zero
where
increment :: a -> Maybe (Tuple a a)
increment a = Just (Tuple a $ add one a)

-- | 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)