tags:

views:

107

answers:

2

Ok this is rather frustrating, I;ve installed the latest version of SharpDevelop, and also installed the F# compiler (as per the link from SharpDevelops website)

I am running in Vista.

thus far, everything has been working fine.

But for some reason it simply refuses to compile when I try to use List.fold_left, however List.fold seems to work,

here is the error:

The value, constructor, namespace or type 'fold_left' is not defined (FS0039)

here is the code:

#light
open System
let nums = [1..10]
let ans = List.fold_left (+) 0 nums
Console.WriteLine("answer: {0}", ans)
// Just to make it pause
let pause = Console.ReadLine()

the further issues is I'm trying to use the fold to square each item in the list eg:

1^2 + 2^2 + 3^2 ...

I assumed that the Fold takes a function and a list, so I've tried as follows:

let sq x = x*x
let ans = List.fold (sq) 0 nums

but this gives me the following error both on the second line:

The type 'int -> int' does not match the type 'int' (FS0001) - The type ''a -> int' does not match the type 'int' (FS0001) -

Please can someone explain this?

+7  A: 

List.fold_left was the old name for the function, which is now List.fold. The problem that you have is that List.fold takes two arguments, the first of which is the function to fold over the list and the second of which is the initial seed for the recursion. The function you use needs to take two arguments, the running total so far and the next element of the list. You want to use something like

List.fold (fun sum x -> sum + x * x) 0 [1..10]

The error you got was just telling you that the type of the function you were trying to use didn't take the right number of arguments.

kvb
So this brings up something I was wondering the other day. Is there a right fold in the standard library?
Nels Beckman
@Nels - Yes, it's called `List.foldBack`.
kvb
And you can find it by looking at the docs I linked in my answer. The library docs are a decent reference - have a look!
Brian
Ah ha! yes that worked, thank you for the explanation!
Darknight
+2  A: 

By the way, the library reference docs are here:

http://msdn.microsoft.com/en-us/library/ee353567.aspx

See e.g.

http://msdn.microsoft.com/en-us/library/ee353738.aspx

(I've forgotten how difficult it can be to develop without Intellisense.)

Also, you can remove the "#light" at the top, it is not needed.

Brian
many thanks for the links, plus the tip about not needing #light. It quite hard without Intellisense, half the time I don't know if I have the syntax correct.
Darknight