Skip to content

Instantly share code, notes, and snippets.

@syusui-s
Last active February 24, 2018 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syusui-s/29d7e21c4baf6f5df5897a8c44a3a718 to your computer and use it in GitHub Desktop.
Save syusui-s/29d7e21c4baf6f5df5897a8c44a3a718 to your computer and use it in GitHub Desktop.
class State
def initialize(&block)
@block = block
end
def self.state(&block)
State.new(&block)
end
def self.put(state)
State.new do |s|
[ nil, state ]
end
end
def self.get
State.new do |s|
[ s, s ]
end
end
def self.ret(val)
State.new do |s|
[ val, s ]
end
end
def flat_map(&f)
State.new do |s|
a, new_state = @block.call(s)
f.call(a).run(new_state)
end
end
def run(initial_state)
@block.call(initial_state)
end
end
# 素で書いた版
#
# push = proc {|val, stack|
# [ nil, stack + [ val ] ]
# }.curry
#
# pop = proc {|stack|
# [ stack[-1], stack[0..-2] ]
# }.curry
# stack = []
# _, stack = push[1, stack]
# _, stack = push[2, stack]
# _, stack = pop[stack]
push = proc {|val|
State.new {|stack|
[ nil, stack + [ val ] ]
}
}.curry
pop = State.new {|stack|
[ stack[-1], stack[0..-2] ]
}
p push[1]
.flat_map{|_|
push[2].flat_map{|_|
push[3].flat_map {|_|
pop
}
}
}
.run([]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment