From: Reimer Behrends Date: 2002-09-06T20:30:30+09:00 Subject: Re: Ruby aesthetics Gavin Sinclair (gsinclair@soyabean.com.au) wrote: [...] > def sqrt(x) > good_enough = lambda { |g1,g2| ((g1 - g2).abs / g2) < .001 } > improve = lambda { |guess| average(guess, x/guess) } > sqrt_iter = lambda { |g1,g2| > (good_enough[g1,g2]) ? g2 : sqrt_iter[g2, improve[g2]] > } > > sqrt_iter[1.0, 2.0] > end If I may suggest something? The natural habitat of a collection of functions and data in an object-oriented system is the class. E.g.: class SqrtNewton def average(a,b) (a+b)/2.0 end # Just enough to make the example run def good_enough(g1,g2) (g1-g2).abs/g2 < .001 end def improve(guess) average(guess, @x/guess) end def sqrt_iter(g1, g2) if good_enough(g1, g2) then g2 else sqrt_iter(g2, improve(g2)) end end def sqrt(x) @x = x sqrt_iter(1.0, 2.0) end end # This also allows us to refine our implementation via # inheritance: class SqrtBetter < SqrtNewton attr_accessor :epsilon def initialize(epsilon=.001) @epsilon = epsilon end def good_enough(g1, g2) (g1-g2).abs/g2 < @epsilon end end SQRT_CALCULATOR = SqrtBetter.new(.0001) def sqrt(x) SQRT_CALCULATOR.sqrt(x) end # We probably want to stick all this inside a module so as not to # pollute the global namespace, but it should be sufficient for # the purposes of this example. The problem with nested definitions is that you have identified an abstraction (the nested defs) that cannot possibly be reused or varied, since they are hidden within that function. Reimer Behrends