Project

General

Profile

Actions

Feature #17576

open

Partial Functions (procs, lambdas)

Added by temabolshakov (Tema Bolshakov) 9 months ago. Updated 9 months ago.

Status:
Open
Priority:
Normal
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

Updated by matz (Yukihiro Matsumoto) 9 months ago

Is there any real-world use-case? I don't see any of them.
Besides that, proposed syntax does not work well with normal blocks.

Matz.

Updated by matheusrich (Matheus Richard) 9 months ago

Kinda reminded me of Elixir's guards.

Actions

Also available in: Atom PDF