From: Florian Frank Date: 2005-10-20T04:06:32+09:00 Subject: Re: Functional with Ruby 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 But using Array#slice for getting the "tail" of the "list" could be inefficient. You could also use my lazylist gem and the do this: require 'lazylist' def list_sum(l) case l when LazyList::Empty then 0 else l.head + list_sum(l.tail) end end list_sum list(1,2,3) That way you can also create an infinite ones lazy list in Ruby with this nice notation: ones = list(1) { ones } # => [1,... ] -- Florian Frank