Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
recurcion_foldBack.rb
#!/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