F#: How to pass two lists in to a formula and return my results?

171 Views Asked by At

So I have this function where i'm taking in two float lists and using their respective index elements to calculate this simple formula: (x-y)^2 / x for every index (0,1,2,3...)

Here is what I have so far:

let myCalc (list1: float list) (list2: float list) : float list  = 
    List.map2 (fun x y -> (x-y)^2 / x) list1 list2

I keep getting this error: This expression was expected to have type 'float' but here has type 'string'

How come my approach listed above won't work but this example does:

let list1 = [1; 2; 3]
let list2 = [4; 5; 6]
let sumList = List.map2 (fun x y -> x + y) list1 list2
printfn "%A" sumList

Can someone explain how I can understand the difference between the code that I've written and the example code listed above? And yes, I already tried setting the List.map2 to a variable and then printing it out but that didn't work either. I think it has something to do with the way I'm doing my calculations, I just don't know what is wrong.

Also, I want my output result to be stored in a list of the respective x and y indexes. Please help.

1

There are 1 best solutions below

0
Foxy On

The reason for this error is relatively simple, you are using the wrong power operator (^). In F #, and in the family of ML languages in general, this operator is a concatenation string operator. This is why you get this error, since the compiler expects to find two parameters of the string type in rvalue and lvalue for the^operator.

You must use the ** operator:

let myCalc (list1: float list) (list2: float list) : float list =
    List.map2 (fun x y -> (x - y) ** 2. / x) list1 list2

2 is a literal of typeint, we have to specify that we want to use a literal value of type float for the expression, so this gives us this:2.

Related Questions in F#