-
Notifications
You must be signed in to change notification settings - Fork 5
/
Supply.hs
47 lines (39 loc) · 1014 Bytes
/
Supply.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{-- snippet LANGUAGE --}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-- /snippet LANGUAGE --}
{-- snippet module --}
module Supply
(
Supply
, next
, runSupply
) where
{-- /snippet module --}
{-- snippet Supply --}
import Control.Monad.State
newtype Supply s a = S (State [s] a)
{-- /snippet Supply --}
{-- snippet deriving --}
deriving (Monad)
{-- /snippet deriving --}
{-- snippet next.type --}
next :: Supply s (Maybe s)
{-- /snippet next.type --}
{-- snippet runSupply.type --}
runSupply :: Supply s a -> [s] -> (a, [s])
{-- /snippet runSupply.type --}
{-- snippet code --}
next = S $ do st <- get
case st of
[] -> return Nothing
(x:xs) -> do put xs
return (Just x)
runSupply (S m) xs = runState m xs
{-- /snippet code --}
{-- snippet showTwo --}
showTwo :: (Show s) => Supply s String
showTwo = do
a <- next
b <- next
return (show "a: " ++ show a ++ ", b: " ++ show b)
{-- /snippet showTwo --}