Project

General

Profile

Actions

Feature #17576

open

Partial Functions (procs, lambdas)

Added by temabolshakov (Tema Bolshakov) almost 4 years ago. Updated about 2 years ago.

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

Description

We already have pattern matching and functions. Let's combine them and introduce a "partial procs" as first-class citizens.

What are partial procs? This is a function that works on a subset of arguments. The partial proc's main advantage is that a caller may decide in advance if this proc can accept an argument or not and do something different rather than calling it.

That's how it may look like:

partial_proc = proc do |arg|
in x if x.odd?
  "#{x} is odd"
end

One can check if a proc is defined on the argument

partial_proc.defined?(42) #=> false
partial_proc.defined?(41) #=> true

You can call such a partial proc and it raises an error when it's not defined on this argument:

partial_proc.call(42) #=> raises NoMatchingPatternError (42)
partial_proc.call(41) #=> 41 is odd

And finally, we can call or fallback to a default value:

partial_proc.call_or_else(42) { "fallback value" } #=> 'fallback value'
partial_proc.call_or_else(41) { "fallback value" } #=> 41 is odd
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0