How to do argument validation of F# records

前端 未结 4 596
执念已碎
执念已碎 2021-01-07 22:24

F# makes it easy to define types such as

type coords = { X : float; Y : float }

but how do I define constraints/check arguments for the con

4条回答
  •  感情败类
    2021-01-07 22:49

    You can make the implementation private. You still get structural equality but you lose direct field access and pattern matching. You can restore that ability using active patterns.

    //file1.fs
    
    type Coords = 
      private { 
        X: float
        Y: float 
      }
    
    []
    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
    

提交回复
热议问题