File tree Expand file tree Collapse file tree 3 files changed +49
-3
lines changed Expand file tree Collapse file tree 3 files changed +49
-3
lines changed Original file line number Diff line number Diff line change @@ -20,6 +20,8 @@ module Control.Monad.List.Trans
20
20
, prepend
21
21
, prepend'
22
22
, repeat
23
+ , runListT
24
+ , runListTRec
23
25
, scanl
24
26
, singleton
25
27
, tail
@@ -70,9 +72,14 @@ data Step a s
70
72
| Skip (Lazy s )
71
73
| Done
72
74
73
- -- | Run a computation in the `ListT` monad.
74
- runListT :: forall f a . ListT f a -> f (Step a (ListT f a ))
75
- runListT (ListT fa) = fa
75
+ -- | Drain a `ListT`, running it to completion and discarding all values.
76
+ runListT :: forall f a . Monad f => ListT f a -> f Unit
77
+ runListT = foldl' (\_ _ -> pure unit) unit
78
+
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
76
83
77
84
-- | The empty list.
78
85
nil :: forall f a . Applicative f => ListT f a
Original file line number Diff line number Diff line change
1
+ module Example.List where
2
+
3
+ import Prelude
4
+ import Data.Array as A
5
+ import Control.Monad.Eff (Eff )
6
+ import Control.Monad.Eff.Class (liftEff )
7
+ import Control.Monad.Eff.Console (CONSOLE , log )
8
+ import Control.Monad.List.Trans (ListT , runListTRec , iterate , takeWhile )
9
+ import Control.MonadZero (guard )
10
+
11
+ -- based on http://hackage.haskell.org/package/list-transformer
12
+ logList :: forall eff .
13
+ ListT (Eff (console :: CONSOLE | eff )) String
14
+ -> Eff (console :: CONSOLE | eff ) Unit
15
+ logList l = runListTRec do
16
+ liftEff $ log " logging listT"
17
+ str <- l
18
+ liftEff $ log str
19
+
20
+ -- based on https://wiki.haskell.org/ListT_done_right#Sum_of_squares
21
+ sumSqrs :: forall eff .
22
+ Int
23
+ -> ListT (Eff (console :: CONSOLE | eff )) Unit
24
+ sumSqrs n = do
25
+ let
26
+ nats = iterate (add one) zero
27
+ squares = takeWhile (_ <= n) $ map (\x -> x * x) nats
28
+ x <- squares
29
+ y <- squares
30
+ liftEff $ log (" <" <> show x <> " ," <> show y <> " >" )
31
+ guard $ x + y == n
32
+ liftEff $ log " Sum of squares."
33
+
34
+ main :: forall eff . Eff (console :: CONSOLE | eff ) Unit
35
+ main = do
36
+ logList $ A .toUnfoldable [" one" , " two" , " three" ]
37
+ runListTRec $ sumSqrs 10
Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ import Example.State as State
11
11
import Example.StateEff as StateEff
12
12
import Example.Writer as Writer
13
13
import Example.RWS as RWS
14
+ import Example.List as List
14
15
15
16
main :: Eff (console :: CONSOLE ) Unit
16
17
main = do
@@ -20,3 +21,4 @@ main = do
20
21
StateEff .main
21
22
Writer .main
22
23
RWS .main
24
+ List .main
You can’t perform that action at this time.
0 commit comments