Project

comp

0.0
No commit activity in last 3 years
No release in over 3 years
A library to add functional composition between Procs and Methods in Ruby.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

~> 3.3
 Project Readme

comp Build Status

A Ruby library to add function composition to Procs (including lambdas) and Methods.

Current version: 1.0.0
Supported Ruby versions: 1.9.2, 1.9.3, 2.0, 2.1, 2.2

Installation

gem install comp -v '~> 1.0'

Or, in your Gemfile:

gem 'comp', '~> 1.0'

Usage

require 'comp'

# Basic usage
add = proc { |x, y| x + y }
double = proc { |x| x * 2 }
double_after_add = double * add

double_after_add.call(1, 2)
#=> 6

# Composing Procs and other callables
class Parser
  def call(json)
    JSON.load(json)
  end
end

extract_name = proc { |attributes| attributes.fetch('name') }
(extract_name * Parser.new).call('{"name": "Alice"}')
#=> "Alice"

Requiring comp will require two files:

  • comp/proc: add Proc#* if it hasn't already been defined;
  • comp/method: add Method#* if it hasn't already been defined.

API Documentation

Proc#*

increment_and_add = proc { |x| x * 2 } * proc { |x| x + 1 }
increment_and_add.call(1)
#=> 4

Composes a Proc (f) with any object that responds to call (g) returning a new Proc which will call g with any given arguments (including blocks) and then call f with the result.

If f was created with lambda, the resulting Proc will also be a lambda.

Method#*

class Number
  def add(x, y)
    x + y
  end

  def double(x)
    x * 2
  end
end

(Number.new.method(:double) * Number.new.method(:add)).call(2, 3)
#=> 10

Composes a Method (f) with any object that responds to call (g) returning a new Proc which will call g with any given arguments (including blocks) and then call f with the result.

Why isn't this in Ruby itself?

Good question: I'd like to change that.

Acknowledgements

License

Copyright © 2015 Paul Mucur.

Distributed under the MIT License.