Skip to content

Commit ed45b90

Browse files
committed
add runListTRec and use in examples
1 parent 3ec1f6d commit ed45b90

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

src/Control/Monad/List/Trans.purs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ module Control.Monad.List.Trans
2121
, prepend'
2222
, repeat
2323
, runListT
24+
, runListTRec
2425
, scanl
2526
, singleton
2627
, tail
@@ -75,6 +76,11 @@ data Step a s
7576
runListT :: forall f a. Monad f => ListT f a -> f Unit
7677
runListT = foldl' (\_ _ -> pure unit) unit
7778

79+
-- | Drain a `ListT`, running it to completion and discarding all values.
80+
-- | Stack safe: Uses tail call optimization.
81+
runListTRec :: forall f a. MR.MonadRec f => ListT f a -> f Unit
82+
runListTRec = foldlRec' (\_ _ -> pure unit) unit
83+
7884
-- | The empty list.
7985
nil :: forall f a. Applicative f => ListT f a
8086
nil = ListT $ pure Done

test/Example/List.purs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,17 @@ module Example.List where
22

33
import Prelude
44
import Data.Array as A
5-
import Data.List.Lazy as L
65
import Control.Monad.Eff (Eff)
76
import Control.Monad.Eff.Class (liftEff)
87
import Control.Monad.Eff.Console (CONSOLE, log)
9-
import Control.Monad.List.Trans (ListT, runListT)
8+
import Control.Monad.List.Trans (ListT, runListTRec, iterate, takeWhile)
109
import Control.MonadZero (guard)
1110

1211
-- based on http://hackage.haskell.org/package/list-transformer
1312
logList :: forall eff.
1413
ListT (Eff (console :: CONSOLE | eff)) String
1514
-> Eff (console :: CONSOLE | eff) Unit
16-
logList l = runListT do
15+
logList l = runListTRec do
1716
liftEff $ log "logging listT"
1817
str <- l
1918
liftEff $ log str
@@ -24,8 +23,8 @@ sumSqrs :: forall eff.
2423
-> ListT (Eff (console :: CONSOLE | eff)) Unit
2524
sumSqrs n = do
2625
let
27-
nats = L.iterate (add one) zero -- lazy infinite list
28-
squares = L.toUnfoldable <<< L.takeWhile (_ <= n) $ map (\x -> x * x) nats
26+
nats = iterate (add one) zero
27+
squares = takeWhile (_ <= n) $ map (\x -> x * x) nats
2928
x <- squares
3029
y <- squares
3130
liftEff $ log ("<" <> show x <> "," <> show y <> ">")
@@ -35,4 +34,4 @@ sumSqrs n = do
3534
main :: forall eff. Eff (console :: CONSOLE | eff) Unit
3635
main = do
3736
logList $ A.toUnfoldable ["one", "two", "three"]
38-
runListT $ sumSqrs 10
37+
runListTRec $ sumSqrs 10

0 commit comments

Comments
 (0)