From: hanmac@... Date: 2019-08-19T12:23:17+00:00 Subject: [ruby-core:94434] [Ruby master Feature#16113] Partial application Issue #16113 has been updated by Hanmac (Hans Mackowiak). the Devs should maybe look at `#curry` for this, currently it doesn't support a way to curry keyword arguments ---------------------------------------- Feature #16113: Partial application https://bugs.ruby-lang.org/issues/16113#change-80859 * Author: zverok (Victor Shepelev) * Status: Open * Priority: Normal * Assignee: * Target version: ---------------------------------------- **Preface:** One of the main "microstructures" of the code we use is chaining methods-with-blocks; and we really love to keep those blocks DRY when they are simple. Currently, for DRY-ing up simple blocks, we have: * `foo(&:symbol)` * `foo(&some.method(:name))` (as of 2.7, `foo(&some.:name)`) * Currently disputed "nameless block args": `foo { something(@1) }` or `foo { something(@) }` or `foo { something(it) }` **Proposal:** I argue that short and easy-to-remember partial application of blocks and methods can make methods-with-blocks much more pleasant and consistent to write, and continue softly shifting Ruby towards "functional" (while staying true to language's spirit). In order to achieve this, I propose method `{Symbol,Method,Proc}#w` (from `with`), which will produce `Proc` with _last_ arguments bound. Example of usability: ```ruby # No-shortcuts: fetch something and parse as JSON: fetch(urls).map { |body| JSON.parse(body) } # Could be already (2.7+) shortened to: fetch(urls).map(&JSON.:parse) # But if you have this: fetch(urls).map { |body| JSON.parse(body, symbolize_names: true) } # How to shorten it, to don't repeat body? # "Nameless block args" answer: fetch(urls).map { JSON.parse(@1, symbolize_names: true) } # Partial application answer: fetch(urls).map(&JSON.:parse.w(symbolize_names: true)) ``` I believe that the latter (while can be easily met with usual "hard to understand for a complete novice") provides the added value of producing proper "functional object", that can be stored in variables and constants, and generally lead to new approaches to writing Ruby code. Another example: ```ruby (6..11).map(&:**.w(2)).map(&:clamp.w(20, 50)) # => [36, 49, 50, 50, 50, 50] ``` Reference implementation: ```ruby class Symbol def w(*args) proc { |receiver, *rest| receiver.send(self, *rest, *args) } end end class Method def w(*args) proc { |receiver, *rest| self.call(receiver, *rest, *args) } end end class Proc def w(*args) prc = self proc { |*rest| prc.call(*rest, *args) } end end ``` -- https://bugs.ruby-lang.org/ Unsubscribe: