From: Brian Candler Date: 2009-01-11T03:11:55+09:00 Subject: Re: functional programming Pascal J. Bourguignon wrote: > Are you saying that you must use lambda everywhere, even when you have a > named function? That named functions are less than anonymous functions? No. I was trying: (1) to understand what the underlying problem was that you were trying to solve in jumping through all these hoops, rather than using lambda { ... } directly, and (2) to understand Mike's assertion that Ruby lambdas are not first-class functions (i.e. "The difference between lambda { } and a real first-class function is quite profound"). >> smallest = lambda { |list| >> smallestElement[list[1..-1], list.first] >> } > > There's a difference between (def smallest(x) ; x ; end) > and (smallest = (lambda { |x| x })) > > In the former case, you can write (smallest [1,2,3]) > in the later you can't: Sure, in the latter you'd write smallest[[1,2,3]]. The outer brackets delimit the call of the lambda, and the inner ones mark the array. > irb(main):003:0> (smallest = (lambda { |x| x })) > (smallest = (lambda { |x| x })) > # > irb(main):004:0> (smallest [1,2,3]) > (smallest [1,2,3]) > (irb):3: warning: multiple values for a block parameter (3 for 1) > from (irb):4 > [1, 2, 3] As far as I can see, it is only accidental that this runs at all. 'smallest' is not a method, it's a local variable, so smallest[...] can only be interpreted as a call to the #[] method on that object, i.e. smallest.call(...) > As you show it, it is perfectly possible to do it this way in ruby. But > it's more complex. You have to know now what this & syntax does. You > have to wonder why you cannot write: > > > (def biggest(x) > ... > end) > > [ > [1], > [1,1,1,1], > [1,2,3,4], > [4,3,2,1], > [1,2,3,4,3,2,1], > [4,3,2,1,2,3,4]].map(&biggest) > > ArgumentError: > wrong number of arguments (0 for 1) > from (irb):17:in `biggest' > from (irb):17 I would have expected map(&method(:biggest)) to work, but unfortunately it doesn't due to arity reasons. I guess you rob Peter to pay Paul. In Ruby, a bareword like "biggest" can be a method name (in which case it invokes the method, and evaluates to its return value), or a variable name (in which case it evaluates to the content of that variable). This means that common cases in Ruby don't need any syntactic markers like () to say "invoke this method". The code just looks cleaner. But in that case, if you want to refer to the *name* of the method or the *method/function itself* then you need to mark in that case instead. i.e. :foo or method(:foo) -- Posted via http://www.ruby-forum.com/.