Car*_*ngo 18 f# constructor record
F#可以很容易地定义类型
type coords = { X : float; Y : float }
Run Code Online (Sandbox Code Playgroud)
但是如何在不进入更详细的类定义语法的情况下为构造函数定义约束/检查参数?例如,如果我想从(0,0)开始coords或抛出异常.
此外,如果我将我的定义更改为类,我需要实现Equals()等所有我不想要的样板代码(以及我在C#中试图摆脱的那些).
Dan*_*iel 18
您可以将实现设为私有.您仍然可以获得结构上的平等,但是会丢失直接的字段访问和模式匹 您可以使用活动模式恢复该功能.
//file1.fs
type Coords =
private {
X: float
Y: float
}
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Coords =
///The ONLY way to create Coords
let create x y =
check x
check y
{X=x; Y=y}
let (|Coords|) {X=x; Y=y} = (x, y)
//file2.fs
open Coords
let coords = create 1.0 1.0
let (Coords(x, y)) = coords
printfn "%f, %f" x y
Run Code Online (Sandbox Code Playgroud)