Hi,
in F# and functional programming in general, you usually work with immutable data structures. This means that you don't modify the existing value (e.g. using Add method). Also, the let mutable is usually used only when doing some optimizations or more tricky things.

In your example, you want to return all numbers that divide "n" without remainder. A functional solution to this problem would be to write a recursive function that looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
// Returns divisors of "n" larger than "from"
let rec divisorsUtil n from =
    if (from > n/2) then []  // no more numbers - return empty list
    else
        let divRest = divisorsUtil n (from + 1) // Get numbers that divide "n" and are larger than "from + 1"
        if (n%from <> 0) then 
            divRest // n is not a divisor, so we just return divisors calculated recursively
        else
            from::divRest // This creates a new list that contians all elemetns from 'divRest' and also the element 'n'

// Let's try it out...
> divisorsUtil 60 2;;
val it : int list = [2; 3; 4; 5; 6; 10; 12; 15; 20; 30]

Note, you could use the "::" operator that constructs new list in your code - you would write something like t <- c::t, which creates a new list and changes the mutable value, but this is not a "clear" functional solution to the problem. If you're comming from the C# background, then you may find that many things are often done differently in F#, so feel free to ask here - learning functional programming is quite interesting experience!

BTW: I should also say that F# gives you a way to construct lists like this more easily. However, this is a bit advanced feature, so I didn't want to start with it. You can simply write:

1
2
3
4
let somefunc n =
    [ for c in 2 .. n/2 do
          if (n%c=0) then do
              yield c ] // "yield" returns another item to be placed to the list that we're creating now..

Hope this helps!
T.

By on 10/28/2008 9:08 AM ()

Thank you very much!!!

By on 10/29/2008 1:30 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper