From: Gavin Sinclair Date: 2002-09-02T07:32:09+09:00 Subject: Re: Ruby aesthetics ----- Original Message ----- From: "Reimer Behrends" > Gavin Sinclair (gsinclair@soyabean.com.au) wrote: > [...] > > > I'll conclude with one (new) feature from Python that makes me green > > with envy: list comprehensions. For those who don't know what that > > means, here's an example: > > > Ruby: squares_less_than_10 = numbers.find_all{|i| i<10}.map{|i| i^2} > > > > Python: squares_less_than_10 = [x^2 for x in numbers if x < 10] > > That calls for a functional abstraction (functional abstraction is > essentially a fancy software engineering term for factoring out commonly > occuring code sequences into a procedure, function, or method of its > own) rather than a new language feature. This abstraction is most easily > added to Enumerable: > > module Enumerable > > # map all elements through a filtering block, keeping all the results > # that aren't nil. > > def condmap > result = [] > each do > | elem | > item = yield elem > result << item unless item.nil? > end > result > end > > end > > To be used as follows: > > squares_less_than_10 = numbers.condmap{|x| x**2 if x < 10 } That's very nice indeed. Would there be any support for adding this, or something like it, to the language standard? Maybe not, since there's a redundancy (collect{...}.compact). But I'd like to see it for sure. > In general, you do not want to expand the language when existing > abstraction mechanisms can already capture the same thing adequately and > with more room for customization. True, but what about getting all pairs of number less than 10 whose combination mulitplies to greater than 25? result = [[a,b] for a in (1...10) for b in (1...10) if a * b > 25] This construct hasn't had much popularity in this thread, but I think it would be a worthwhile addition to the language. It's simply a beautiful abstraction. (I know a little about functional programming, but cannot be said to have a background in it: my appreciation for list comprehensions is more mathematical.) > Reimer Behrends Gavin