Tuesday, August 16, 2011

PES - Project Euler 9

A particularly interesting feature of f# is its lazy types. A lazy type is something that doesnt get executed all the time. It gets evaluated only when necessary. At all other times it just gets passed around. In this problem, the objective is to find a particular Pythagorean triple .

Here is a function that calculates a Pythagorean triple given m and n such that m > n.
    let PythagorTriple m n =
            m*m - n*n, 2*m*n, n*n + m*m


Now using unfold    
    let triples =
        Seq.unfold (fun (m,n) ->
                        let triple = PythagorTriple m n
                        let nextmn = if n+1>m then (m+1,1) else (m,n+1)
                        Some(triple,nextmn)
                    )(2,1)
    triples
    |> Seq.find(fun (a,b,c) -> a+b+c = 1000)
    |> fun(a,b,c) -> a*b*c

No comments: