From: "Ara.T.Howard" Date: 2005-10-20T13:01:58+09:00 Subject: Re: Functional with Ruby On Thu, 20 Oct 2005, Dave Burt wrote: > > "Ara.T.Howard" wrote in message > news:Pine.LNX.4.62.0510191259580.28380@harp.ngdc.noaa.gov... >> On Thu, 20 Oct 2005, Andreas Semt wrote: >> >>> Hello list, >>> >>> here a really simple Haskell function, which sums all elements of a list >>> (from the book "The Haskell School of Expression"): >>> -------------------------------- >>> listSum [] = 0 >>> listSum (x : xs) = x + listSum xs >>> -------------------------------- >>> >>> Which is the best way to say it in Ruby (functional style)? Don't use >>> 'enum.inject', please! >> >> >> harp:~ > cat a.rb >> list_sum = lambda{|*list| list.flatten!; list.empty? ? 0 : list.shift + >> list_sum[list] } >> >> p list_sum[ 0b101000, 0b10 ] >> >> harp:~ > ruby a.rb >> 42 > > OK, this is the first actually functional post -- list_sum is a first-class > function. > > Here's my translation: > > list_sum = Proc.new {|x, *xs| if x then x + list_sum[*xs] else 0 end } nice. still the functional vs. non is a very thin line in ruby: harp:~ > cat a.rb class << self def list_sum x = nil, *xs x ? x + list_sum(*xs) : 0 end end list_sum = method 'list_sum' p list_sum[0b101000, 0b10] p list_sum[42] p list_sum[] harp:~ > ruby a.rb 42 42 0 ps. i'm trying to wrap my mind around ocaml attm. regards. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | anything that contradicts experience and logic should be abandoned. | -- h.h. the 14th dalai lama ===============================================================================