For what's is worth, I've blogged about the folding functions here, [link:natehoellein.blogspot.com]

By on 1/28/2008 4:40 PM ()

Nate,

Whoa! That blog of yours is going to take more than a few minutes to absorb! It looks like great information but at this point in my learning (and comfort with) F# it's somewhat of a struggle for me. Thanks so much for pointing it out, I will definitely be spending some time there.

Mitchell

By on 1/28/2008 5:30 PM ()

Yes, that is the standard way to do it (and won't be much longer than your own function). Here's how you can sum a list:

1
2
3
List.fold_left (+) 0 lst
List.fold1_left (+) lst // only if you're sure there are 2 or more elements
List.sumByInt (fun x -> x) lst

If you want to define your own function, you can always do something like:

1
2
3
let lints = List.fold_left (+) 0
let lfloats = List.fold_left (+) 0.
let lbis = List.fold_left (+) 0I

These will work on lists of integers, floats and bigints, respectively. You can probably make a polymorphic version, although I've found it easier to just customize each version for their respective situation.

Regards,

z.

By on 1/27/2008 10:47 PM ()

z,

Thanks again. Can you tell me what that "o" is for?

Mitchell

By on 1/28/2008 5:06 AM ()

Do you mean the zero? That's the value you're folding into, so to speak. With fold, there always has to be an initial value for the "accumulator," which then gets passed to each invocation of the function.

By on 1/28/2008 10:23 AM ()

Guitarist,

I just can't tell my o's from my 0's. However, given what you said what about z's line:

List.fold1_left (+) lst // only if you're sure there are 2 or more elements

Why wouldn't you need to start with a zero there?

Mitchell

By on 1/28/2008 12:51 PM ()

List.fold1_left uses the first element from the list as the initial value.

By on 1/28/2008 1:09 PM ()

Dustin,

Thanks!

Mitchell

By on 1/28/2008 2:10 PM ()
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