31 August 2009

Haskell agus Tionscadal Euler #2

Seo an chéad phost sa tsraith seo.

Mo réiteach féin do uimhir a do:

fib 1 = 1
fib 2 = 2
fib n = (fib (n-1)) + (fib (n-2))

fiblist = map fib [1..]

shortlist = takeWhile (< 4000000) fiblist
main = print ( sum[n | n <- shortlist, n `mod` 2 == 0] )

Ach nuair a léigh mé an foram agus cúpla suíomh eile, fuair mé cúpla fheabhsú:

fiblist = 0 : 1 : (zipWith (+) fiblist (tail fiblist))
shortlist = takeWhile (< 4000000) fiblist
main = print ( sum[n | n <- shortlist, even n] )

Fuair mé an sainmhíniú Fibonacci is cliste ón alt seo.

If you're wondering what this is all about, here's the first post in this series. The first bit of code is my own solution; the second is a much better one that I found on the forum.

1 comment:

danny said...

Bhí siad súd ró-fhada agus casta. An rud a scríos féin ná:

main = print (sum (map fib [3, 6.. 33]))

Gan dabht bhí an sainmhíniú chéana agam.
Agus go n-éirí leat leis na cinn eile.