Skip to content

Week 4 Lecture 2

lec08.hs:

hs
1
import Control.Monad (ap, liftM)
2
import Data.IORef (IORef)
3
import System.Posix (otherExecuteMode)
4
5
data Test = Test
6
{ a :: Int
7
, b :: Int
8
, c :: Int
9
}
10
deriving (Show)
11
12
data Free f a = Pure a | Free (f (Free f a))
13
14
instance (Functor f) => Functor (Free f) where
15
fmap = liftM
16
17
-- fmap f m = m >>= pure . f
18
19
instance (Functor f) => Applicative (Free f) where
20
pure = Pure
21
(<*>) = ap
22
23
instance (Functor f) => Monad (Free f) where
24
(Pure a) >>= f = f a
25
(Free cont1) >>= f = Free $ (>>= f) <$> cont1
26
27
data StateOps s c = GetState (s -> c) | PutState s c deriving (Functor)
28
29
type FreeState s = Free (StateOps s)
30
31
-- ╭----- Technically `x` can only ever be `Free f a`,
32
-- ↓ but using "forall" makes certain guarantees that we desire
33
interpret :: (Monad m, Functor f) => (forall x. f x -> m x) -> Free f a -> m a
34
interpret _transform (Pure a) = pure a
35
interpret transform (Free cont) = transform cont >>= interpret transform
36
37
-- @Doboz, where does the original state go? isn't Put just put some value in?
38
-- We may need some of the originals, no? That's what the s does, isnt' it?
39
-- For the _s (Free StatePut s' m)
40
-- then you don't need _s, because it gets overwritten, no? not just appended? no, that's Writer :catthink:, But how does StatePut know of the original s? Or you reduced the computation until StatePut has s built in? Why would you need the original s in StatePut?
41
-- So another Get in m can get values from state. How does that relate to Put? It's continuation passing style, so Put itself only contains what needs to happen after the current action.
42
43
-- Fibonacci S3 database when?
44
45
-- Kotlin mentioned letsgoooo
46
47
-- @Doboz, qq: can we later generate haskell source code from these free constructors? Like macro definitions at rust...
48
-- But you already have haskell source code? I mean like extracting the data constructors and compile it to the monad you want to use. Like a framework. So you'd get equivalent code, but ✨faster✨? yes. I guess it's not impossible. You could also just use a typeclass instead of a free monad lmfao
49
-- Always the typeclasses, but in case some random weirdos do that, can I fix it purely on the syntax level?..
50
-- I guess there's nothing stopping you. You can actually do it right in haskell through template haskell. from what I've seen, it's actually more powerful than Rust's macros. it's pretty cool
51
-- hmmm, can this be the goal of the usage of free here?
52
-- Haskell frameworks
53
-- no
54
55
-- Space