Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# under SharpDevelop

Tags:

list

f#

fold

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?

like image 739
Darknight Avatar asked Aug 16 '26 04:08

Darknight


1 Answers

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.

like image 77
kvb Avatar answered Aug 18 '26 20:08

kvb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!