
Summing it up
February 24, 2007Today, 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|
sum+=line.to_i
end
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.
Cool
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})Nice!
perl, mooi:
$i += $_ while ();
print $i;
Damn, accidentally omitted code tags.