Skip to content

Instantly share code, notes, and snippets.

@kwatch
Created July 20, 2012 01:35
Show Gist options
  • Select an option

  • Save kwatch/3148115 to your computer and use it in GitHub Desktop.

Select an option

Save kwatch/3148115 to your computer and use it in GitHub Desktop.
Sequenceを作る関数をPythonとRubyで書いてみた
##
## Python
##
def seq(initial, formula):
x = initial
while True:
yield x
x = formula(x)
sequence = seq(1, lambda x: x+1)
print(next(sequence)) #=> 1
print(next(sequence)) #=> 2
print(next(sequence)) #=> 3
##
## Ruby
##
def seq(initial, &formula)
x = initial
Enumerator.new do |yielder|
loop {
yielder << x
x = yield x
}
end
end
sequence = seq(1) {|x| x+1 }
puts sequence.next #=> 1
puts sequence.next #=> 2
puts sequence.next #=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment