Skip to content

Instantly share code, notes, and snippets.

/ruby.rb Secret

Created August 25, 2016 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/d06deb09a98955f68dcb3cc99d90bcbf to your computer and use it in GitHub Desktop.
Save anonymous/d06deb09a98955f68dcb3cc99d90bcbf to your computer and use it in GitHub Desktop.
# From http://combinators.info/#recursive-combinators-in-idiomatic-ruby
def lambda_with_recursive_callback
lambda { |x| x.call(x) }.call(
lambda do |myself|
lambda do |arg|
yield(arg, myself.call(myself))
end
end
)
end
sum_of_nested_list = lambda_with_recursive_callback do |arg, recurse|
arg.kind_of?(Numeric) ? arg : arg.map { |item| recurse.call(item) }.injec\
t(&:+)
end
sum_of_nested_list.call([1, [[2,3], [[[4]]]]])
#=> 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment