From: Dave Burt Date: 2005-10-20T11:26:59+09:00 Subject: Re: Functional with Ruby "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 } Cheers, Dave