Project

General

Profile

Actions

Feature #15302

open

Proc#with and Proc#by, for partial function application and currying

Added by RichOrElse (Ritchie Buitre) over 5 years ago. Updated over 5 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:89791]

Description

Proc#by allows currying implicitly

class Proc
  def by(*head)
    return self if head.none?
    curry(head.size.next).(*head)
  end
end

class Method
  def by(*head)
    to_proc.by(*head)
  end
end

class Symbol
  def by(*head)
    to_proc.by(*head)
  end
end

double = :*.by(2) # => proc { |n| 2 * n }

Proc#with pre-defines trailing arguments and/or block.

class Proc
  def with(*tail, &blk)
    if arity == tail.size.next
      proc { |head| call head, *tail, &blk }
    else
      proc { |*head| call *head, *tail, &blk }
    end
  end
end

class Method
  def with(*head, &blk)
    to_proc.with(*head, &blk)
  end
end

class Symbol
  def with(*head, &blk)
    to_proc.with(*head, &blk)
  end
end

double = :*.with(2) # => proc { |n| n * 2 }

That's the basic idea, but I've also expanded on it by optimising and defining operators (+, &, |) and other methods (Proc#such) here.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0