Feature #9401
openYet another syntax for literal anonymous functions (lambdas)
Description
Please do not be angry at me and just close this proposal if it does not look interesting. It comes from my aesthetic dissatisfaction with the ->(x){ ... }
literal anonymous function notation and from my amateurish interest in lambda calculus.
Here is a yet another syntax for literal anonymous functions (lambdas) that i propose:
f = {\ x => x*x }
f[1] # => 1
f[2] # => 4
It looks a bit like a hash on purpose: i think that a hash is a "function in extension" and a lambda is a "function in intension" (see, for example, in these notes). The backslash stands for "lambda", like in Haskell.
Updated by alexeymuranov (Alexey Muranov) almost 11 years ago
An anonymous "function" (not really a function) without arguments would be like this:
timer = {\=> Time.now }
Maybe there is no need to make it look so much like a hash, so the following looks to me like a good option either:
f = {\ x -> x*x }
timer = {\-> Time.now }
Updated by alexeymuranov (Alexey Muranov) almost 11 years ago
I have realized that the backslash may conflict with explicit line continuation. In that case, "almost any" symbol would work to distinguish a "lambda" from a hash. For example: {^ x => x*x }
. (I've read that initially Church wrote x̂
-- "x-hat", and not λx
.)
Updated by alexeymuranov (Alexey Muranov) almost 11 years ago
Nobuyoshi Nakada wrote:
What about
(^x) {x*x}
?
I think, my initial attempt was closer to lambda calculus notation (λx(x*x))
or (λx.x*x)
, to its modern variant x ⟼ x*x
, to Haskell \x -> x*x
, to Ruby block syntax {|x| x*x }
, and to Ruby hash syntax { 2 => 2*2 }
.
Another option: make it openly similar to the block syntax: {\|x| x*x }
or {^|x| x*x }
. Other options:
-
{<x> x*x }
,{<> Time.now }
, -
{<x>=> x*x }
, -
{|x|=> x*x }
, -
{|x|> x*x }
be a proc and{|x|-> x*x }
be a lambda.
Also, a double backslash would not conflict with a line break:
-
{\\ x => x*x }
,{\\=> Time.now }
.
Sorry, i cannot choose myself the best syntax, i just do not like ->(x){ ... }
(strange placement of the "arrow", and it looks like a method call with a block, but the block parameters are mysteriously missing from the block and are found outside in parentheses, where arguments would be expected).
Edited 2014-04-03
Updated by hsbt (Hiroshi SHIBATA) almost 3 years ago
- Project changed from 14 to Ruby master