From: Mike Gold Date: 2009-01-13T13:22:16+09:00 Subject: Re: functional programming Brian Candler wrote: > > You could have written the lambda to take a single Array argument: > This is another repeat of previous comments by others in this thread. I'll say for at least the third time now: the point is that the lambda is given -- you cannot change it. Since the requisite attention has waned, it may be time to give up. But I will try one more approach. The idea of functional programming is to use higher-order functions to get the job done. It's like using The Force. You aren't allowed to pick up the rock. You have to concentrate, reach out with The Force, and make it rise into the air without touching it. You can only use higher-order functions. Initially, you may not be very productive compared to others who are using their hands to move rocks. Eventually, however, you are able to move 100 rocks at once, far surpassing your manual-labor counterparts. The analogy is exaggerated, but it serves to convey the idea. Say we wish to add these pairs together, data = [[1,2], [3,4], [5, 6]] Here is the manual approach -- grabbing the rock with your hands: data.map { |x, y| x + y } #=> [3, 7, 11] The only problem is that it's very specific to this one case. We've used 'map', which is a heck of a lot better than not using it, but the code could still be more general. Now let's try using The Force. First we need some helper functions. def splatter(func) lambda { |args| func.call(*args) } end def binder(method) lambda { |*args| method.bind(args[0]).call(*args[1..-1]) } end All right, here we go: data.map(&splatter(binder(Fixnum.instance_method(:+)))) #=> [3, 7, 11] Note how general this is. I can use any method from anywhere (not just from Fixnum), with any set of data. This even works with the 'mean' function which failed before, mean = lambda { |*args| (args.inject(0) { |acc, x| acc + x })/args.size.to_f } [[1,2,3], [4,5,6,7]].map(&splatter(mean)) #=> [2.0, 5.5] So a functional language is one tailed for programming in this manner: using higher-order functions, reaching out with The Force. It is awkward in Ruby, but not in functional languages which were designed for it. Unfortunately the only way to really understand what I mean is to practice programming in a functional language. The basics of Haskell can be learned pretty quickly, I think. I thought this was a fun book: http://learnyouahaskell.com . -- Posted via http://www.ruby-forum.com/.