From: Edward Faulkner Date: 2005-10-20T04:00:39+09:00 Subject: Re: Functional with Ruby --tThc/1wpZn/ma/RB Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Oct 20, 2005 at 03:41:09AM +0900, 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 [] =3D 0 > listSum (x : xs) =3D x + listSum xs > -------------------------------- >=20 > Which is the best way to say it in Ruby (functional style)? Don't use > 'enum.inject', please! But inject *is* functional! It's equivalent to Lisp's accumulate. It doesn't modify the list at all or have any side-effects. =20 Perhaps you're asking for a function that takes the list as an argument, rather than a method that operates on the lisp. For example: def listsum(x) x.size =3D=3D 0 ? 0 : x[0] + listsum(x[1..-1]) end This looks more like the Haskell, but it's not idiomatic for Ruby. It only looks like a standalone function, it's really a method on Object. Ruby can be used this way, but it's going against the grain. The Ruby way is definitely x.inject {|a,b| a + b}, or if you'll be using it a lot: class Array def sum inject {|a,b| a+b} end end regards, Ed --tThc/1wpZn/ma/RB Content-Type: application/pgp-signature; name="signature.asc" Content-Description: Digital signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) iD8DBQFDVpc+nhUz11p9MSARAhsVAKCNQqlhz4GaN2qt7x5gIW0xNha9WQCgxfOZ BNNtYxI3JqeWzjnVKDfHFfM= =CzLz -----END PGP SIGNATURE----- --tThc/1wpZn/ma/RB--