Writer
Functions
instance Monad ((->) r) where
return x = \\_ -> x
h >>= f = \\w -> f (h w) w
- 함수의 Context는 무엇일까? → '아직 입력값이 주어지지 않았음'
import Control.Monad.Instances
addStuff :: Int -> Int
addStuff = do
a <- (*2)
b <- (+10)
return (a+b)
- Monad임을 이용해서, 아직 입력값이 주어지지 않았음에도 불구하고 결과로 나올 값들을 a, b에 할당해서 사용할 수 있음
State
- stateful computation
- 어떠한 상태를 받아서, 결과값과 다음 상태를 반환
s → (a,s)
- Stack 예시
type Stack = [Int]
pop :: Stack -> (Int,Stack)
pop (x:xs) = (x,xs)
push :: Int -> Stack -> ((),Stack)
push a xs = ((),a:xs)
stackManip = do
push 3
a <- pop
pop
- State(=Stateful Computation) Monad
- return문 : 주어진 값과 기존 상태를 그대로 반환하는 함수
- h s 를 통해서 기존 state에서 값과 새로운 상태 추출 (a, newState)
- f a 를 통해서 값에 (a → m b) 함수를 적용하여 새로운 monadic value 생성
- 새로운 monadic value g 함수에 새로운 상태 적용
newtype State s a = State { runState :: s -> (a,s) }
instance Monad (State s) where
return x = State $ \\s -> (x,s)
(State h) >>= f = State $ \\s -> let (a, newState) = h s
(State g) = f a
in g newState
import Control.Monad.State
pop :: State Stack Int
pop = State $ \\(x:xs) -> (x,xs)
push :: Int -> State Stack ()
push a = State $ \\xs -> ((),a:xs)
stackManip :: State Stack Int
stackManip = do
push 3
a <- pop
pop
Random
random :: (RandomGen g, Random a) ⇒ g → (a, g)