Function Type Function F #

This is the first F # line I tried writing, so I apologize because I probably just don't know the right Google keywords to search.

I tried to define a function like this:

let sigmoid x deriv = if deriv then x * (1 - x) else 1 / (1 + System.Math.Exp(-x)) 

This gives me an error on System.Math.Exp(-x) :

 The type 'float' does not match the type 'int' 

I assume that I expected the compiler to make type inference in this function and define x as a float. What am I missing here?

Here is what I am trying to connect:

 let sigmoid x deriv = if deriv then x * (1 - x) else 1 / (1 + System.Math.Exp(-x)) [<EntryPoint>] let main argv = sigmoid 1.0 false |> printfn "%A" 0 
+6
source share
1 answer

The compiler reports x as an int because you used it in things like 1 - x . Prime 1 will always be an integer, and you can use it only in arithmetic expressions along with other integers. Your code compiles if you change all of your usages 1 to 1.0 , which will make it float and cause x be output as float .

This is different from C #, for example, which will force types if necessary, and thus allows you to mix integers and floating point numbers in the same expressions. This can lead to an accidental loss of accuracy under certain circumstances, although F # always forces you to specify any necessary conversions explicitly.

+6
source

Source: https://habr.com/ru/post/1013963/


All Articles