Posts

....
Technical Blog for .NET Developers ©

Saturday, January 21, 2017

F# : Recursive loops

Recursive functions is one of key concepts of functional programming. F# prefix these functions with keyword rec

In this sample we have defined three functions, two of them recursives, and one of them returning a type int list. The result is the factorization of the number in parameter

Algorithm gets a lot simplified by step in the logic of factorization. This is the algorithm translated to F#



        let divide x s = (x % s) = 0

        let rec lowFactor x s = if (divide x s) then s else lowFactor x (s + 1)

        let rec factorize x =
            [
                if (x <> 1) then

                    let i = lowFactor x 2

                    yield i

                    if (divide x i) then

                        for k in factorize (x / i) do

                            yield k

            ]

        let tst = factorize 108416 


<METHOD SOFTWARE 2020 ©>