New question f #

My simple function call takes two tuples. Getting a compiler error by type:

module test

open System.IO
open System

let side (x1,y1) (x2,y2) : float = 
  Math.Sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1))

let a = side ( 2s, 3s ) ( 1s, 2s )

Error 2 Type "float" does not match type "int16"

I don’t know where this is happening. Can anyone help?

Thank!

+3
source share
3 answers

Math.Sqrt expects a float argument, but you pass int16 there. F # does not perform such implicit conversions

let side (x1,y1) (x2,y2) : float = 
    (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
    |> float
    |> Math.Sqrt

or you can pass floats from the start:

let side (x1,y1) (x2,y2) : float = Math.Sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1))

let a = side ( 2.0, 3.0 ) ( 1.0, 2.0 )
+6
source

As others have already pointed out, the F # compiler does not automatically insert any conversions between numeric types. This means that if you write a function that works with float, you need to pass it a float as arguments.

, Math.Sqrt . , , ( Math.Sqrt ):

> let side (x1,y1) (x2,y2) = 
    Math.Sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));;
val side : float * float -> float * float -> float

floats , , . , , . :

> let side (x1:int16,y1) (x2,y2) = 
    let n = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
    Math.Sqrt(float(n));;
val side : int16 * int16 -> int16 * int16 -> float

( , y1, x2,... int16, / ). , :

side ( 2s, 3s ) ( 1s, 2s ) 

, desco - ​​ ( float), - , int, , , side (2,3) (1,2).

+6

The signature of your function float * float -> float * float -> float, but you pass the values int16(which means suffix s).

One way to compile it is to do this:

let a = side ( 2.0, 3.0 ) ( 1.0, 2.0 )
+3
source

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


All Articles