Class: Fear::For
- Inherits:
-
Object
- Object
- Fear::For
- Defined in:
- lib/fear/for.rb
Overview
This class provides syntactic sugar for composition of multiple monadic operations. It supports two such operations - flat_map and map. Any class providing them is supported by For.
For(a: Some(2), b: Some(3)) { a * b } #=> Some(6)
If one of operands is None, the result is None
For(a: Some(2), b: None()) { a * b } #=> None()
For(a: None(), b: Some(2)) { a * b } #=> None()
Lets look at first example:
For(a: Some(2), b: Some(3)) { a * b }
would be translated to:
Some(2).flat_map do |a|
Some(3).map do |b|
a * b
end
end
It works with arrays as well
For(a: [1, 2], b: [2, 3], c: [3, 4]) { a * b * c }
#=> [6, 8, 9, 12, 12, 16, 18, 24]
would be translated to:
[1, 2].flat_map do |a|
[2, 3].flat_map do |b|
[3, 4].map do |c|
a * b * c
end
end
end
Defined Under Namespace
Modules: Mixin
Instance Method Summary collapse
- #call(&block) ⇒ Object
-
#initialize(**variables) ⇒ For
constructor
A new instance of For.
Constructor Details
#initialize(**variables) ⇒ For
Returns a new instance of For.
71 72 73 |
# File 'lib/fear/for.rb', line 71 def initialize(**variables) @variables = variables end |
Instance Method Details
#call(&block) ⇒ Object
77 78 79 80 |
# File 'lib/fear/for.rb', line 77 def call(&block) variable_name_and_monad, *tail = *variables execute({}, *variable_name_and_monad, tail, &block) end |