From: "Hal E. Fulton" Date: 2002-09-04T02:40:53+09:00 Subject: Re: Ruby aesthetics ----- Original Message ----- From: "Drew Mills" To: "ruby-talk ML" Sent: Tuesday, September 03, 2002 10:51 AM Subject: RE: Ruby aesthetics > I must confess to a lack of Ruby guru-ness. It would be a great tutorial if > someone would be gracious enough to give a token-by-token (blow-by-blow > sounds so violent) commentary on what Reimer just wrote. It's not token-by-token, but maybe this will enlighten a little. His condmap ("conditional map") behaves just like the built-in map, *except* that it filters out nil values. I.e., if you take out the "unless item.nil?", what you have is a simple reimplementation of map. If you're not familiar with map: It basically takes an array and produces a related array by performing the same operation on each element (synonym for collect). If it's the iterator part you don't get: The 'yield' basically calls whatever block is given to the condmap call. Control is in effect traded back and forth (like coroutines) between the iterator and the block. Reimer's whole argument (if I understand him) is that things which are easily implemented should not be added to the core unnecessarily. His condmap is easily implemented and is easily changed if we decide later we want to filter out other values besides nil. Help any? Hal > > > -----Original Message----- > > From: Reimer Behrends [mailto:behrends@cse.msu.edu] > > Sent: Sunday, September 01, 2002 5:59 PM > > To: ruby-talk ML > > Subject: Re: Ruby aesthetics > > > > > > 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 } > > > > 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. > > > > Reimer Behrends > > >