Class: Functor
Overview
:title: Functor
By definition a Functor is simply a first class method, but these are common in the form of Method and Proc. So here a Functor is a bit more specialied as a 1st class metafunction. Essentally, a Functor can vary its behavior accorrding to the operation applied to it.
Synopsis
require 'mega/functor'
f = Functor.new { |op, x| x.send(op, x) }
f + 1 #=> 2
f + 2 #=> 4
f + 3 #=> 6
f * 1 #=> 1
f * 2 #=> 2
f * 3 #=> 9
Notes
It would probably be a little better if we had a kernelless base object class. Built-in public Object methods will not work in a Functor b/c of this. Or perhaps this can improved via delegation.
Author(s)
-
Thomas Sawyer
Instance Method Summary collapse
-
#initialize(&func) ⇒ Functor
constructor
A new instance of Functor.
- #method_missing(op, *args) ⇒ Object
Constructor Details
#initialize(&func) ⇒ Functor
Returns a new instance of Functor.
53 54 55 |
# File 'lib/mega/functor.rb', line 53 def initialize(&func) @func = func end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(op, *args) ⇒ Object
56 57 58 |
# File 'lib/mega/functor.rb', line 56 def method_missing(op, *args) @func.call(op, *args) end |