Summing it up

February 24, 2007

Today, I had a list of integers, and I wanted to sum it up. I guessed that I should write a script in Ruby, to make sure it would get done within 2 minutes. So I fired up my editor, and wrote the following script:

sum = 0 ;
$stdin.each do |line|
puts sum

Pretty straightforward. I’d rather had written the script in Haskell, but I figured I needed to get things done. This evening I tried the same thing in Haskell, but to I was surprised: it was even quicker and more straightforward than the Ruby version! Here it is:

main = interact $ show . sum . map read . lines

If you’d like more of these tiny tools, see Haskell Unix Tools.



  1. Cool 🙂

  2. I you would seperate the numbers by something other than newlines (spaces for instance), this would be a more concise Ruby implementation:

    puts(gets.split(' ').inject {|x,y| x.to_i + y.to_i })

    If you have implemented the Symbol::to_proc method, the following would be even more elegant:

    puts(gets.split(' ').map(&:to_i).inject {|x,y|x+y})

  3. Nice!

  4. perl, mooi:

    $i += $_ while ();
    print $i;

  5. Damn, accidentally omitted code tags.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: