Warm tip: This article is reproduced from stackoverflow.com, please click
f#

F#: Specifying a custom type in function declaration (complex number to pair)

发布于 2020-04-16 11:57:43

I've specified a custom type which takes two floats and makes them a pair (a complex number):

type complex = (float * float);;

let makeComplex x y = complex(x,y);;

The makeComplexfunction is of type float -> float -> complex, which is entirely correct. However, I want to create a function that takes a complex type and makes it a normal pair as well. This is the function I've tried:


let complexToPair ((x,y):complex) = (x,y);;

But the resulting type is float * float -> float * float, when it should really be complex -> float * float. Am I using the wrong syntax for the ((x,y):complex)part?

Questioner
ConradDoggo
Viewed
45
glennsl 2020-02-04 14:15

Type abbreviations do not hide or create a type distinct from their definitions. complex and float * float are still fully exchangeable, You've just given it another name.

The idiomatic way to make a distinct type in F# is to use a single-case discriminated union:

type complex = Complex of float * float

You can then write your functions using this constructor to create a value and pattern matching to deconstruct it:

let makeComplex x y = Complex (x,y)
let complexToPair (Complex (x, y)) = (x, y)

You can also hide the implementation completely from outside the module using private:

type complex = private Complex of float * float

Consumers would then have to use the functions you expose to create and consume values of the complex type.