Created
July 20, 2012 01:35
-
-
Save kwatch/3148115 to your computer and use it in GitHub Desktop.
Sequenceを作る関数をPythonとRubyで書いてみた
This file contains hidden or 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
| ## | |
| ## 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