Last active
February 11, 2017 18:00
-
-
Save cema-sp/373b5b9f1afb4ceeab343aa6ef4aba3c to your computer and use it in GitHub Desktop.
Print Integers 1 to N without loops and conditions
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
#!/usr/bin/env ruby | |
def upto_n(n) | |
e = Enumerator.new do |y| | |
f = -> (x) { yield x; y << x; f[x + 1] } | |
f[1] | |
end | |
e.take(n) | |
end | |
# ------ main ------ | |
n = ARGV[0]&.to_i | |
upto_n(n) { |x| puts x } |
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
#!/usr/bin/env ruby | |
def upto_n(n) | |
f = lambda do |x| | |
yield x | |
begin | |
_dangerous = 1 / (n - x) | |
f[x + 1] | |
rescue ZeroDivisionError | |
# quit recursion on error | |
end | |
end | |
f[1] | |
end | |
# ------ main ------ | |
n = ARGV[0]&.to_i | |
upto_n(n) { |x| puts x } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment