Last active
August 30, 2017 22:12
-
-
Save serradura/e1f44a28da88c7ffb37da06357b7e506 to your computer and use it in GitHub Desktop.
Ruby FP extensions (Pipe and Compose operators)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Composable | |
def pipe(other) | |
-> (*args) { other.(self.(*args)) } | |
end | |
alias >> pipe | |
def compose(other) | |
-> (*args) { self.(other.(*args)) } | |
end | |
alias << compose | |
end | |
Proc.send(:include, Composable) | |
Method.send(:include, Composable) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sum = -> a, b { a + b } | |
double = -> a { a * 2 } | |
piped_double_sum = sum >> double | |
composed_double_sum = double << sum | |
puts piped_double_sum.(1, 2) # 6 | |
puts composed_double_sum.(2, 1) # 6 | |
invalid_arity_to_double_sum = sum << double | |
invalid_arity_to_double_sum.(1, 2) | |
# ArgumentError: wrong number of arguments (given 2, expected 1) | |
class Calc | |
def initialize(a) | |
@a = a | |
end | |
def plus(b) | |
@a + b | |
end | |
end | |
two = Calc.new(2) | |
puts two.plus(1) # 3 | |
add2 = two.method(:plus) | |
add2_and_double = add2 >> double | |
puts add2_and_double.(3) # 10 | |
piped_add2_and_double = sum.curry[2] >> double | |
composed_add2_and_double = double << sum.curry[2] | |
puts piped_add2_and_double.(3) # 10 | |
puts composed_add2_and_double.(3) # 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment