如何在 F# 中创建状态

约塞连船长

F#初学者在这里。我说初学者?这是我使用 F# 的第二天)

我只想记录两种状态:有效和无效;我想让非法国家无法代表。

这是我的代码:

module Foo =
    type Success = Success of string
    type Pending = Pending of string
    type Failure = Failure of string

    type Valid = Valid of string
    type InValid = InValid of string

    type StateGranted = { Status: Valid; Msg: Success }
    type StateDenied = { Status: InValid; Msg: Failure }

    type State =
        | StateGranted
        | StateDenied

    let status = Valid "Valid"
    let msg = Success "Success"

    let state = { Status = status; Msg = msg } // I have an error here

    printfn "result %A" state

那么,如何创建类型的记录State如果用户想要创建

let state = { Status = Valid; Msg = Pending } // compiler should throw an error here

我有打字稿背景

PS我找到了非常有用的文章,但我还不明白

查尔斯·罗迪

我建议在 F# 中处理一个很清楚你想要实现的项目。您需要让自己清楚什么是合法数据。

  1. 目前尚不清楚该Success类型代表什么是否Success "Invalid"合法?这适用于所有前五种类型,这些都可以删除。

  2. 当您尝试定义时,state您可能希望 StateGranted 和 StateDenied 都是有效的可能性。但这些不是同一类型。您需要定义一个单一的类型来表示state可能存在的事物

这将您的代码简化为:

[<RequireQualifiedAccess>]
type State =
    | Granted // possibly you mean for there to be string-like data here
    | Denied
    // or possibly there are string functions of it like
    //member t.ValidityString =
    //    match t with
    //    | Granted -> "Valid"
    //    | Denied -> "Denied"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章