Hi, first post to clr here.

I have a guess a haskell bias as that’s the last language I learned,

and now I’m learning ruby.

I was trying to solve project euler problem 2 as an exercise. This is,

sum all the even fibonacci numbers less than 4 million.

There is a solution that works at

http://www.absorbeo.net/2008/01/10/project-euler-problem-2/

however I didn’t quite like it because the test for evenness is in the

fold (haskell speak for inject).

puts a.inject(0) {|s,v|

if v > 1_000_000 then

break s

elsif v % 2 == 0

s+v

else

s

end

}

the haskell solution reads nicer to me

t = ( putStrLn . show . sum . takeWhile (<=4000000) . filter even )

fibs2

fibs2 = 1 : 2 : zipWith (+) fibs2 (tail fibs2)

but it relies on laziness and who knows what other magic.

I decided to see if I could find a ruby solution that was more

haskellish. It turns I can… almost.

There is a ruby library for laziness

# http://lazylist.rubyforge.org/

and it would seem to do what I want. But it hangs for some reason.

I have poor sense of ruby culture. Should I report this as a bug? Is

it even a bug? Do people ever use laziness, or is this crazy

experimentation?

Thanks for help and advice!

Code below:

thartman@thartman-laptop:~/thomashartman-learning/ruby/katas/euler>cat

2.rb

require ‘rubygems’

require ‘lazylist’ # http://lazylist.rubyforge.org/

# Solve Project Euler problem 2: sum fibonacci numbers <= 4_000_000,

which are even.

fibs = ( LazyList.tabulate(0) { |x| x < 2 ? 1 : fibs[x-2] +

fibs[x-1] } )

fibsUnder4M = ( fibs.partition{ |x| x <= 4_000_000 })[0]

evenFibsUnder4M = fibsUnder4M.select{ |x| x %2 == 0}

# problem seems to be with partition

# evenFibsLessThanFourMil = ( evenFibs.partition{ |x| x <= 4_000_000 })

[0]

# works

# puts evenFibsLessThanFourMil.take(1)

# hangs

puts evenFibsUnder4M.take(10) # this is ok

puts evenFibsUnder4M.take(11) # this hangs, laptop gets hot, fan turns

on…

# exit

# this would be the answer to the euler problem, if only there wasn’t

the bug…

result = evenFibsLessThanFourMil.inject(0){ | accum,val | accum + val}

main = puts result

thartman@thartman-laptop:~/thomashartman-learning/ruby/katas/

euler>ruby 2.rb

2

8

34

144

610

2584

10946

46368

196418

832040

… hung…