Skip to content

Instantly share code, notes, and snippets.

@akanehara
Created November 19, 2012 07:02
Show Gist options
  • Save akanehara/4109333 to your computer and use it in GitHub Desktop.
Save akanehara/4109333 to your computer and use it in GitHub Desktop.
Listモナドこうですか?わかりません><
concat = (xss) ->
ys = []
for xs in xss
for x in xs
ys.push(x)
ys
# Listモナドのつもり
class List
constructor: (@xs) ->
bind: (f) ->
new List(concat (f(x).xs for x in @xs))
toString: -> @xs.toString()
# 値構築子
# 引数1個でreturn相当
$L = (xs...) -> if xs? then new List(xs) else new List([])
# 真のとき (>>) の左単位元 [()]
# 偽のとき (>>) の零元 [] を返す
guard = (b) -> if b then $L(null) else $L()
# という言い方が合ってるのかどうか自信ない
# [ x * y | x <- [2,5,10], y <- [8,10,11], 50 < x * y]
# のつもり
alert $L(2,5,10).bind((x) ->
$L(8,10,11).bind((y) ->
guard(50 < x * y).bind( ->
$L(x*y))))
# モナディック関数の合成 (<=<)
compositeM = (g, f) ->
(x) -> f(x).bind((x) -> g(x))
# compositeM のてすと
f = (x) -> $L(x,x*2)
g = (x) -> $L(x+1, x+2, x+3)
alert $L(1,2,3).bind(compositeM(g, f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment