Created
June 25, 2016 07:09
-
-
Save tomcha/045268f405b4917d8b8ed44c51be3609 to your computer and use it in GitHub Desktop.
recurcion_foldBack.rb
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 | |
# coding:utf-8 | |
list = [1, 2, 3, 4] | |
sumproc = Proc.new{|initval, enum| | |
initval + enum | |
} | |
minproc = Proc.new{|initval, enum| | |
initval > enum ? enum : initval | |
} | |
maxproc = Proc.new{|initval, enum| | |
initval < enum ? enum : initval | |
} | |
def foldBack(list, initval, sumproc) | |
if list.size == 0 | |
initval | |
else | |
enum = list.shift | |
calcresult = sumproc.call(initval, enum) | |
foldBack(list, calcresult, sumproc) | |
end | |
end | |
puts foldBack(list.clone, 0, sumproc) | |
puts foldBack(list.clone, list[0], minproc) | |
puts foldBack(list.clone, list[0], maxproc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment