Skip to content

Commit

Permalink
Merge pull request #85 from purescript/rec-many-some
Browse files Browse the repository at this point in the history
Add `MonadRec` versions of `many` and `some`
  • Loading branch information
garyb authored Oct 28, 2016
2 parents ccd3edd + dd4d4a1 commit 48ca7c5
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Data/List.purs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ module Data.List
, singleton
, (..), range
, some
, someRec
, many
, manyRec

, null
, length
Expand Down Expand Up @@ -90,7 +92,9 @@ import Prelude
import Control.Alt ((<|>))
import Control.Alternative (class Alternative)
import Control.Lazy (class Lazy, defer)
import Control.Monad.Rec.Class (class MonadRec, Step(..), tailRecM)

import Data.Bifunctor (bimap)
import Data.Foldable (class Foldable, foldr, any, foldl)
import Data.List.Types (List(..), (:))
import Data.List.Types (NonEmptyList(..)) as NEL
Expand Down Expand Up @@ -143,6 +147,10 @@ range start end | start == end = singleton start
some :: forall f a. (Alternative f, Lazy (f (List a))) => f a -> f (List a)
some v = Cons <$> v <*> defer (\_ -> many v)

-- | A stack-safe version of `some`, at the cost of a `MonadRec` constraint.
someRec :: forall f a. (MonadRec f, Alternative f) => f a -> f (List a)
someRec v = Cons <$> v <*> manyRec v

-- | Attempt a computation multiple times, returning as many successful results
-- | as possible (possibly zero).
-- |
Expand All @@ -151,6 +159,15 @@ some v = Cons <$> v <*> defer (\_ -> many v)
many :: forall f a. (Alternative f, Lazy (f (List a))) => f a -> f (List a)
many v = some v <|> pure Nil

-- | A stack-safe version of `many`, at the cost of a `MonadRec` constraint.
manyRec :: forall f a. (MonadRec f, Alternative f) => f a -> f (List a)
manyRec p = tailRecM go Nil
where
go :: List a -> f (Step (List a) (List a))
go acc = do
aa <- (Loop <$> p) <|> pure (Done unit)
pure $ bimap (_ : acc) (\_ -> reverse acc) aa

--------------------------------------------------------------------------------
-- List size -------------------------------------------------------------------
--------------------------------------------------------------------------------
Expand Down

0 comments on commit 48ca7c5

Please sign in to comment.