如何做F#记录的参数验证 [英] How to do argument validation of F# records

查看:134
本文介绍了如何做F#记录的参数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

F#可以轻松定义类型,例如

F# makes it easy to define types such as

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

但是如何为构造函数定义约束/详细类定义语法?例如。如果我想要协调从(0,0)开始或抛出异常。

but how do I define constraints/check arguments for the constructor without going into the more verbose class definition syntax? E.g. if I want coords to start from (0,0) or throw an exception.

此外,如果我将我的定义更改为类,我需要实现Equals 。所有的锅炉板代码我不想(和我在C#中,我试图逃避)。

Moreover, if I change my definition to a class I need to implement Equals() etc. all the boiler plate code I don't want (and which I have in C# that I'm trying to get away from).

推荐答案

您可以将实现设为私有。你仍然得到结构上的平等,但是你失去了直接的字段访问和模式匹配。您可以使用有效模式恢复该功能。

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 
  }

[<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

这篇关于如何做F#记录的参数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆