Skip to content

Commit 3586dc4

Browse files
committed
Add StateF data type for Free (StateF s) a
* The State s a is Just a Free (StateF s) a
1 parent 16d5770 commit 3586dc4

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/FreeX.hs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ get :: State s s
265265
get = State $ \s -> (s, s)
266266

267267
put :: s -> State s ()
268-
put s = State $ \s -> ((), s)
268+
put s = State $ \_ -> ((), s)
269269

270270
{-
271271
instance (Show s, Show a) => Show (State s a) where
@@ -291,6 +291,21 @@ instance Monad' (State s) where
291291
monad' (Free state) = State $ \s -> let (a, s1) = runState state s
292292
in runState (monad' a) s1
293293

294+
-- The State s a is Just a Free (StateF s) a
295+
data StateF s a = GetF (s -> a)
296+
| PutF s a
297+
298+
instance Functor (StateF s) where
299+
fmap f (GetF g) = GetF (f . g)
300+
fmap f (PutF s a) = PutF s (f a)
301+
302+
type State' s = Free (StateF s)
303+
304+
runState' :: Free (StateF s) a -> s -> (a, s)
305+
runState' (Pure a) s = (a, s)
306+
runState' (Free (GetF g)) s = runState' (g s) s
307+
runState' (Free (PutF s' frm)) s = runState' frm s'
308+
294309
data StackF k = Push Int k
295310
| Pop k
296311
| Top (Int -> k)
@@ -317,6 +332,7 @@ calc = do
317332
pure x
318333

319334
type MemState = State [Int]
335+
type MemState' = State' [Int]
320336

321337
-- | This function is used for demostrate f = free f . ins
322338
interp :: (Functor f, Monad m) => (f :~> m) -> (Free f :~> m)
@@ -335,6 +351,14 @@ phiRun (Top ik) = (State $ \s -> ((safeHead s), s)) >>= return . ik
335351
phiRun (Add k) = (State $ \s@(x:y:ts) -> ((), (x + y) : ts)) >> return k
336352
phiRun (Mul k) = (State $ \s@(x:y:ts) -> ((), (x * y) : ts)) >> return k
337353
-}
354+
-- runState (interp phiRun calc) []
355+
356+
phiRun' :: StackF a -> MemState' a
357+
phiRun' (Push a k) = Free (GetF $ \s -> Free $ PutF (a:s) (Pure k))
358+
phiRun' (Pop k) = Free (GetF $ \s -> Free $ PutF (safeTail s) (Pure k))
359+
phiRun' (Top ik) = Free (GetF $ \s -> Free $ PutF s (Pure $ ik $ safeHead s))
360+
phiRun' (Add k) = Free (GetF $ \s@(x:y:ts) -> Free $ PutF ((x + y) : ts) (Pure k))
361+
phiRun' (Mul k) = Free (GetF $ \s@(x:y:ts) -> Free $ PutF ((x * y) : ts) (Pure k))
338362

339363
phiShow :: StackF k -> Writer String k
340364
phiShow (Push a k) = Writer (k, "Push " ++ show a ++ ", ")

0 commit comments

Comments
 (0)