---
title: Free Monads Getting Started
tags:  #haskell #scala #関数型プログラミング #free monad  
author: [Kent OHASHI](https://www.docswell.com/user/lagenorhynque)
site: [Docswell](https://www.docswell.com/)
thumbnail: https://bcdn.docswell.com/page/2JVMGM9RJQ.jpg?width=480
description: Freeモナド入門 Haskell/ScalaでFreeモナドを使ってみよう(*&gt; ᴗ •*)ゞ
published: May 26, 17
canonical: https://www.docswell.com/s/lagenorhynque/KXYEVX-free-monads-getting-started
---
# Page. 1

![Page Image](https://bcdn.docswell.com/page/2JVMGM9RJQ.jpg)

Free Monads
Getting Started


# Page. 2

![Page Image](https://bcdn.docswell.com/page/5EGG8GZ6EL.jpg)

Self-introduction
lagénorhynque /laʒenɔʁɛ k
̃ / カマイルカ
(defprofile lagénorhynque
:name
&quot;Kent OHASHI&quot;
:account
@lagenorhynque
:company
&quot;Opt, Inc.&quot;
:languages
[Clojure Haskell Python Scala
English français Deutsch русский]
:interests
[programming language-learning mathematics]
:contributing [github.com/japan-clojurians/clojure-site-ja])


# Page. 3

![Page Image](https://bcdn.docswell.com/page/4JQX9XL2EP.jpg)

Contents
1. What are monads?
2. What are Free monads?
3. Example: RPN expressions


# Page. 4

![Page Image](https://bcdn.docswell.com/page/K746X6DPE1.jpg)

What are monads?


# Page. 5

![Page Image](https://bcdn.docswell.com/page/LJ1VNVZXEG.jpg)

de nition of Monad
GHC.Base#Monad
class Applicative m =&gt; Monad m where
(&gt;&gt;=)
:: forall a b. m a -&gt; (a -&gt; m b) -&gt; m b
(&gt;&gt;)
:: forall a b. m a -&gt; m b -&gt; m b
m &gt;&gt; k = m &gt;&gt;= \_ -&gt; k
{-# INLINE (&gt;&gt;) #-}
return
return
:: a -&gt; m a
= pure
fail
fail s
:: String -&gt; m a
= errorWithoutStackTrace s
cf. scalaz/Monad.scala


# Page. 6

![Page Image](https://bcdn.docswell.com/page/GJWL4L9KE2.jpg)

return
値 a をモナド m に⼊れる
Haskell: return
a -&gt; m a
Scalaz: point
A =&gt; M[A]


# Page. 7

![Page Image](https://bcdn.docswell.com/page/4EZM2M9NJ3.jpg)

bind
値 m a に 関数 a -&gt; m b を適⽤して m b にする
Haskell: &gt;&gt;=
m a -&gt; (a -&gt; m b) -&gt; m b
Scalaz: bind (cf. flatMap)
M[A] =&gt; (A =&gt; M[B]) =&gt; M[B]


# Page. 8

![Page Image](https://bcdn.docswell.com/page/Y76NVNK97V.jpg)

do notation (Haskell)
a = Just 2
b = Just 3
c = do
x &lt;- a
y &lt;- b
return $ x * y
↓ desugar
a = Just 2
b = Just 3
c = a &gt;&gt;= (\x -&gt;
b &gt;&gt;= (\y -&gt;
return $ x * y))


# Page. 9

![Page Image](https://bcdn.docswell.com/page/G755D5PD74.jpg)

for expression (Scala)
val a = Some(2)
val b = Some(3)
val c = for {
x &lt;- a
y &lt;- b
} yield x * y
↓ desugar
val a =
val b =
val c =
b.map
x *
}
}
Some(2)
Some(3)
a.flatMap { x =&gt;
{ y =&gt;
y


# Page. 10

![Page Image](https://bcdn.docswell.com/page/9J2N8NZMER.jpg)

What are Free monads?


# Page. 11

![Page Image](https://bcdn.docswell.com/page/DEYP6PRPEM.jpg)

de nition of Free
Control/Monad/Free.hs
data Free f a = Pure a | Free (f (Free f a))
instance Functor f =&gt; Monad (Free f) where
return = pure
{-# INLINE return #-}
Pure a &gt;&gt;= f = f a
Free m &gt;&gt;= f = Free ((&gt;&gt;= f) &lt;$&gt; m)
cf. scalaz/Free.scala


# Page. 12

![Page Image](https://bcdn.docswell.com/page/VJN5Z5DM78.jpg)

リストのような再帰的データ構造
data [] a = [] | a : [a]
f が Functor ⇒ Free f は Monad
→ Functor のインスタンスを Free で包めば
Monad として扱える
※ GHC拡張で Functor を⾃動導出することも:
DeriveFunctor


# Page. 13

![Page Image](https://bcdn.docswell.com/page/YE9YZYGWJ3.jpg)

Example: RPN expressions


# Page. 14

![Page Image](https://bcdn.docswell.com/page/GE8616VR7D.jpg)

repositories
lagenorhynque/freemonad-hs
FreeMonad/RPNExpr.hs
cf. lagenorhynque/freemonad-scala
freemonad/RPNExpr.scala


# Page. 15

![Page Image](https://bcdn.docswell.com/page/LEL9Q952JR.jpg)

RPN: Reverse Polish Notation
逆ポーランド記法 - Wikipedia
861-*2+
↓ with parentheses
((8 (6 1 -) *) 2 +)
↓ evaluate
42


# Page. 16

![Page Image](https://bcdn.docswell.com/page/4JMZ1Z39EW.jpg)

DSL interpreter
RPN DSL = AST -- Free monad
→ eval :: AST -&gt; Num
→ stringify :: AST -&gt; String
← parse :: String -&gt; AST


# Page. 17

![Page Image](https://bcdn.docswell.com/page/PJR6L6Q979.jpg)

RPNのASTを表現するデータ型 RPNExpr を定義する
data RPNExpr n expr = Number n expr
| Add expr
| Sub expr
| Mul expr
| End
deriving (Show)


# Page. 18

![Page Image](https://bcdn.docswell.com/page/PEXMWM537X.jpg)

RPNExpr を Functor にする
instance
fmap
fmap
fmap
fmap
fmap
Functor (RPNExpr n)
f (Number n expr) =
f (Add expr)
=
f (Sub expr)
=
f (Mul expr)
=
_ End
=
where
Number n $ f expr
Add $ f expr
Sub $ f expr
Mul $ f expr
End


# Page. 19

![Page Image](https://bcdn.docswell.com/page/3EKGVG6NJD.jpg)

RPNExpr を Free で包んで RPN Monad として扱う
type RPN a b = Free (RPNExpr a) b
liftF :: (Functor f) =&gt; f r -&gt; Free f r
liftF = Free . fmap Pure
num
num
add
add
sub
sub
mul
mul
end
end
:: a -&gt; RPN a ()
n = liftF $ Number n ()
:: RPN a ()
= liftF $ Add ()
:: RPN a ()
= liftF $ Sub ()
:: RPN a ()
= liftF $ Mul ()
:: RPN a b
= liftF End


# Page. 20

![Page Image](https://bcdn.docswell.com/page/L73NMN6Z75.jpg)

RPN モナド(RPNのDSL = AST)を試してみる
&gt;
|
|
|
|
|
|
|
|
:{
expr1 :: RPN Double ()
expr1 = do
num 8
num 6
num 1
sub
mul
:}
&gt; expr1
Free (Number 8.0 (Free (Number 6.0 (Free (Number 1.0
(Free (Sub (Free (Mul (Pure ()))))))))))


# Page. 21

![Page Image](https://bcdn.docswell.com/page/87DW6WV4JG.jpg)

&gt;
|
|
|
|
|
|
:{
expr2 :: RPN Double ()
expr2 = do
num 2
add
end
:}
&gt; expr2
Free (Number 2.0 (Free (Add (Free End))))
複数の式を連結してみる
&gt; expr1 &gt;&gt; expr2
Free (Number 8.0 (Free (Number 6.0 (Free (Number 1.0
(Free (Sub (Free (Mul (Free (Number 2.0 (Free (Add
(Free End))))))))))))))
&gt; :t expr1 &gt;&gt; expr2
expr1 &gt;&gt; expr2 :: Free (RPNExpr Double) ()
-- RPN Double ()


# Page. 22

![Page Image](https://bcdn.docswell.com/page/VJP9Y9VVE8.jpg)

RPNのASTを⽂字列化する関数 stringify
stringify
stringify
stringify
stringify
stringify
stringify
stringify
:: (Show a) =&gt; RPN a b -&gt; String
(Free (Number n e)) = show n ++ &quot; &quot; ++ stringify e
(Free (Add e))
= &quot;+ &quot; ++ stringify e
(Free (Sub e))
= &quot;- &quot; ++ stringify e
(Free (Mul e))
= &quot;* &quot; ++ stringify e
(Free End)
= &quot;.&quot;
(Pure _)
= &quot;&quot;


# Page. 23

![Page Image](https://bcdn.docswell.com/page/2EVMGMZREQ.jpg)

&gt; expr1
Free (Number 8.0 (Free (Number 6.0 (Free (Number 1.0
(Free (Sub (Free (Mul (Pure ()))))))))))
&gt; stringify expr1
&quot;8.0 6.0 1.0 - * &quot;
&gt; expr2
Free (Number 2.0 (Free (Add (Free End))))
&gt; stringify expr2
&quot;2.0 + .&quot;
&gt; stringify $ expr1 &gt;&gt; expr2
&quot;8.0 6.0 1.0 - * 2.0 + .&quot;


# Page. 24

![Page Image](https://bcdn.docswell.com/page/57GG8G467L.jpg)

⽂字列をRPNのASTに変換する関数 parse
parse :: (Read a) =&gt; String -&gt; Either String (RPN a ())
parse = foldM rpn (Pure ()) . reverse . words
where
rpn e &quot;+&quot; = Right . Free $ Add e
rpn e &quot;-&quot; = Right . Free $ Sub e
rpn e &quot;*&quot; = Right . Free $ Mul e
rpn _ &quot;.&quot; = Right $ Free End
rpn e n
= case reads n of
[(v,_)] -&gt; Right . Free $ Number v e
_
-&gt; Left &quot;invalid input&quot;


# Page. 25

![Page Image](https://bcdn.docswell.com/page/4EQX9XG27P.jpg)

&gt; parse &quot;8.0 6.0 1.0 - * &quot; :: Either String (RPN Double ())
Right (Free (Number 8.0 (Free (Number 6.0 (Free (Number 1.0
(Free (Sub (Free (Mul (Pure ())))))))))))
&gt; parse &quot;2.0 + .&quot; :: Either String (RPN Double ())
Right (Free (Number 2.0 (Free (Add (Free End)))))
&gt; parse &quot;8.0 6.0 1.0 - * 2.0 + .&quot; :: Either String (RPN Double ())
Right (Free (Number 8.0 (Free (Number 6.0 (Free (Number 1.0
(Free (Sub (Free (Mul (Free (Number 2.0 (Free (Add
(Free End)))))))))))))))
&gt; parse &quot;2.0 3.0 /&quot; :: Either String (RPN Double ())
Left &quot;invalid input&quot;


# Page. 26

![Page Image](https://bcdn.docswell.com/page/KJ46X65P71.jpg)

RPNのASTを評価する関数 eval
eval :: (Num a) =&gt; RPN a b -&gt; Either String a
eval = calc []
where
calc stack
(Free (Number n e)) = calc (n : stack) e
calc (n1:n2:ns) (Free (Add e))
= calc (n2 + n1 : ns) e
calc (n1:n2:ns) (Free (Sub e))
= calc (n2 - n1 : ns) e
calc (n1:n2:ns) (Free (Mul e))
= calc (n2 * n1 : ns) e
calc (n:_)
(Free End)
= Right n
calc (n:_)
(Pure _)
= Right n
calc _
_
= Left &quot;invalid expression&quot;


# Page. 27

![Page Image](https://bcdn.docswell.com/page/LE1VNVWX7G.jpg)

&gt; expr1
Free (Number 8.0 (Free (Number 6.0 (Free (Number 1.0
(Free (Sub (Free (Mul (Pure ()))))))))))
&gt; eval expr1
Right 40.0
&gt; expr2
Free (Number 2.0 (Free (Add (Free End))))
&gt; eval expr2
Left &quot;invalid expression&quot;
&gt; eval $ expr1 &gt;&gt; expr2
Right 42.0


# Page. 28

![Page Image](https://bcdn.docswell.com/page/GEWL4L6K72.jpg)

データ型を定義して Functor にすることで、
Free を介して Monad が得られた
例えば
データ型として定義したASTをモナドに
⇒ 合成可能なDSL(= モナド)が提供できる
⇒ AST(= モナド)を解釈する関数群を⽤意する
ことでインタプリタが書ける


# Page. 29

![Page Image](https://bcdn.docswell.com/page/47ZM2MYNE3.jpg)

Further Reading
Haskell for all: Why free monads matter
独習 Scalaz
Free Monad
猫番
⾃由モナド (Free)
『Scala関数型デザイン＆プログラミング』/
Functional Programming in Scala
第13章 外部作⽤とI/O


# Page. 30

![Page Image](https://bcdn.docswell.com/page/YJ6NVND9JV.jpg)

free: Monads for free
Control/Monad/Free.hs
scalaz/scalaz
scalaz/Free.scala
typelevel/cats
cats/free/Free.scala


# Page. 31

![Page Image](https://bcdn.docswell.com/page/GJ55D53DJ4.jpg)

Interpreter パターン - Wikipedia
『すごいHaskellたのしく学ぼう！』/ Learn You a
Haskell for Great Good!
10.1 逆ポーランド記法電卓
14.6 安全な逆ポーランド記法電卓を作ろう
MP in Scala
cf. MP in Haskell
Functor, Applicative, Monadのシンプルな定式化


