Skip to content

seadowg/matilda-function

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

#matilda-function

Build Status

Installation

Add this line to your application's Gemfile:

gem 'matilda-function'

And then execute:

$ bundle

Description

This library provides extensions to Ruby's Proc to allow for some functional goodness.

Composition

So we can pretend we are coding in Haskell we use the << operator for composition on Procs:

sort = proc { |array| array.sort }
reverse = proc { |array| array.reverse }

reverese_order = sort << reverse
reverese_order.call [3,1,4,8] #=> [8,4,3,1]

When we combine two Procs using << we create a new Proc that will first execute the receiver Proc and then pass the result to the argument Proc. This provides an expressive and modular approach to creating complex high order functons in Ruby.

You can also combine Procs using the + operator. This allows you to stack 'side-effecty' operations:

log = proc { |model| Logger.log("Saving #{model}") }
save_to_db = proc { |model| Database.save(model) }

save_model = log + save_to_db
save_model.call(model)

Recursive

Recursive calls are pretty easy in Ruby: lambdas, Procs and methods can all reference themselves. However, these recursive calls will deepen the Ruby call stack. Enter the recursive method:

recursive { |this|
  this.call
}

Blocks passed to recursive will unroll returning recursive calls so that the recursion can execute without eating up the Ruby call stack. This allows for infinitely recursive operations. Here's a quick example:

inf_marco = recursive { |this, shout|
  puts shout

  if shout == "Marco"
    this.call("Polo")
  else
    this.call("Marco")
  end
end

recursive.call("Marco") # => "Marco"
# => "Polo"
# => "Marco"
# => "Polo"
# ...

About

Enhancement to Ruby Procs to allow for some wholesome Functional goodness.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages