From: "David A. Black" Date: 2005-10-21T11:26:53+09:00 Subject: Re: Functional with Ruby Hi -- On Thu, 20 Oct 2005, Florian Frank wrote: > Andreas Semt wrote: > >> 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! >> > > You can abuse Ruby arrays for lists: > > def list_sum(l) > case l > when [] then 0 > else l.first + list_sum(l[1, l.size]) > end > end > list_sum([1,2,3]) # => 6 Just for fun I was trying to see how visually close I could get to the Haskell. The answer is... not very :-) But the star operator actually handles the x : xs list thing rather well: def list_sum(x,*xs) case xs when []: x # note: not 0 when done this way else x + list_sum(*xs) end end David -- David A. Black dblack@wobblini.net