@@ -265,7 +265,7 @@ get :: State s s
265
265
get = State $ \ s -> (s, s)
266
266
267
267
put :: s -> State s ()
268
- put s = State $ \ s -> (() , s)
268
+ put s = State $ \ _ -> (() , s)
269
269
270
270
{-
271
271
instance (Show s, Show a) => Show (State s a) where
@@ -291,6 +291,21 @@ instance Monad' (State s) where
291
291
monad' (Free state) = State $ \ s -> let (a, s1) = runState state s
292
292
in runState (monad' a) s1
293
293
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
+
294
309
data StackF k = Push Int k
295
310
| Pop k
296
311
| Top (Int -> k )
@@ -317,6 +332,7 @@ calc = do
317
332
pure x
318
333
319
334
type MemState = State [Int ]
335
+ type MemState' = State' [Int ]
320
336
321
337
-- | This function is used for demostrate f = free f . ins
322
338
interp :: (Functor f , Monad m ) => (f :~> m ) -> (Free f :~> m )
@@ -335,6 +351,14 @@ phiRun (Top ik) = (State $ \s -> ((safeHead s), s)) >>= return . ik
335
351
phiRun (Add k) = (State $ \s@(x:y:ts) -> ((), (x + y) : ts)) >> return k
336
352
phiRun (Mul k) = (State $ \s@(x:y:ts) -> ((), (x * y) : ts)) >> return k
337
353
-}
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))
338
362
339
363
phiShow :: StackF k -> Writer String k
340
364
phiShow (Push a k) = Writer (k, " Push " ++ show a ++ " , " )
0 commit comments