missingfaktor <[email protected]> wrote:

> Text of the problem: Each new term in the Fibonacci sequence is generated
> by adding the previous two terms. By starting with 1 and 2, the first 10
> terms will be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... . By considering the
> terms in the Fibonacci sequence whose values do not exceed four million,
> find the sum of the even-valued terms.
>
> My solution:
>
> : million ( n -- n' ) 1000000 * ;
> : fibonacci ( n -- seq ) 0 1 rot '[ dup _ < ] [ swap over + dup ] produce
> 2nip ; ! Where has "tuck" gone?!
> 4 million fibonacci [ even? ] filter sum
>
> Any comments on how it can be simplified or made more idiomatic?
>
> --
> Cheers,
> missingfaktor <http://twitter.com/#!/missingfaktor>.
>

Well, first of all, your fibonacci word overshoots: 4000000 fibonacci last
. -> 5702887

Second, you could make it more readable like this:

> USE: locals

: next-fib ( a b -- b c ) [ + ] keep swap ; inline
>
:: fibs-until ( n -- seq ) 0 1 [ dup n < ] [ [ next-fib ] keep ] produce
> 2nip ;
>

Or you could go imperative route with:

> :: euler-2 ( n -- sum )
>     0 :> sum!
>     0 1
>     [ dup even? [ [ sum + sum! ] keep ] when next-fib dup n < ] loop
>     2drop
>     sum
> ;


This saves some time and memory, as Factor isn't lazy and this doesn't work
as well as Haskell's

> let fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

infixr 9 !>
> infixr 9 !
> (!) = flip (.)
> (!>) = flip ($)

let euler2 = fibs !> takeWhile (<4000000) ! filter even ! sum
------------------------------------------------------------------------------
Learn Windows Azure Live!  Tuesday, Dec 13, 2011
Microsoft is holding a special Learn Windows Azure training event for 
developers. It will provide a great way to learn Windows Azure and what it 
provides. You can attend the event by watching it streamed LIVE online.  
Learn more at http://p.sf.net/sfu/ms-windowsazure
_______________________________________________
Factor-talk mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/factor-talk

Reply via email to