Last active
February 24, 2018 06:08
-
-
Save syusui-s/29d7e21c4baf6f5df5897a8c44a3a718 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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