2008

2007

Language choice

▁ jan 02 2008

So many languages, so many choices.

Python

reduce( lambda sum, current: sum + current, [1, 2, 3] )

Common Lisp

(reduce #'+ '(1 2 3))

Ruby

[1, 2, 3].inject(0) { |sum, current| sum = sum + current }

Perl

map {$sum += $_;} (1,2,3);

Which one do you prefer?

Update: I changed the Common Lisp version from using lambda to using the + function instead, it’s a lot less verbose. Thanks to everyone who pointed that out. ;)

← Previous: Cleaning up pydoc (work in progress), take two  //  Next: Implementation of a blog in Common Lisp: Part 1

comments

anon, 1 year ago:

In Common Lisp, `+’ is a function.

(reduce #’+ ‘(1 2 3))

Ingvar, 1 year ago:

Hm, (reduce #’+ ‘(1 2 3)) should be just about equivalent to your slightly more verbose version.

dnm, 1 year ago:

(reduce #’+ ‘(1 2 3)) is just shorter and more readable than the perl.

The Ruby code is pretty ugly.

oudeis, 1 year ago:

I’d prefer this, in Common Lisp: (reduce #’+ ‘(1 2 3))

nefreat, 1 year ago:

IMO Haskell has a very elegant way to do reduce:

foldl(+) 0 [1,2,3]

how about (apply #’+ ‘(1 2 3))

bessides, python has built-in function called sum:

sum([1,2,3])

Justin Grant, 12 months ago:

Ruby could be little shorter [1, 2, 3].inject(0) { |sum, current| sum += current }

Tzury: Python’s sum() is only equivalent to reduce() when addition is performed so they aren’t the same.

The Lisp version is like hearing a symphony…

Brendan Baldwin, 12 months ago:

The ruby code could be shorter than Justin Grant’s example. No assignment necessary.

[1,2,3].inject(0){|sum, current| sum + current}

Brendan Baldwin, 12 months ago:

also… if you wrote an Enumerable method called reduce:

module Enumerable def reduce(method) result, *items = to_a items.each do |item| result = result.send(item) end result end end

then you could easily say: [1,2,3].reduce(:+) # <= 6 [1,2,3,4].reduce(:*) # <= 24

Ed Symanzik, 11 months, 2 weeks ago:

(+ 1 2 3)

powered by