当我只声明一个选项参数时,为什么需要提供两个选项参数?

时间:2017-07-07 12:12:56

标签: f#

当我只声明一个选项参数时,为什么我需要提供两个选项参数?

我声明了以下类型:

type MiddleName =    MiddleName of string option

为了让编译器满意,我必须提供Some case值两次:

let middleName = Some <| MiddleName (Some "Kevin")

注意:我希望只提供一次案例值。

因此,我认为我应该这样做:

let middleName = MiddleName (Some "Kevin")

我甚至做得对吗? 因此,中间名应该是可选的,因此,我试图对其进行建模。

附录

type FirstName =     FirstName  of string
type LastName  =     LastName   of string
type MiddleName =    MiddleName of string option
type MaidenName =    MaidenName of string option
type Email =         Email      of string
type Phone =         Phone      of string

type Name = {
    FirstName:FirstName
    LastName:LastName
    MiddleName:MiddleName option
    MaidenName:MaidenName option
}

let someName = {
    FirstName=FirstName "Scott"
    LastName= LastName "Nimrod"
    MiddleName = Some <| MiddleName (Some "Kevin")
    MaidenName = None

}

1 个答案:

答案 0 :(得分:5)

您已声明MiddleName类型是可选字符串,但您也已将MiddleName成员声明为可选字符。所以你有一个包含可选字符串的可选MiddleName

不需要其中一个optional后缀。请注意,这也适用于MaidenName

您可以从这样的成员中删除该选项(请参阅this fiddle):

type Name = 
    { FirstName : FirstName
      LastName : LastName
      MiddleName : MiddleName
      MaidenName : MaidenName }

let someName = 
    { FirstName = FirstName "Scott"
      LastName = LastName "Nimrod"
      MiddleName = MiddleName (Some "Kevin")
      MaidenName = MaidenName None }

或者来自此MiddleName / MaidenName类型(请参阅this fiddle):

type MiddleName = MiddleName of string
type MaidenName = MaidenName of string

type Name = 
    { FirstName : FirstName
      LastName : LastName
      MiddleName : MiddleName option
      MaidenName : MaidenName option }

let someName = 
    { FirstName = FirstName "Scott"
      LastName = LastName "Nimrod"
      MiddleName = Some (MiddleName "Kevin")
      MaidenName = None }