如何向选项类型转发?

时间:2018-01-31 20:33:16

标签: f#

如何从字符串创建some string

我正在浏览F# Koans tutorials,我是否坚持这一点:

[<Koan>]
let ProjectingValuesFromOptionTypes() =
    let chronoTrigger = { Name = "Chrono Trigger"; Platform = "SNES"; Score = Some 5 }
    let halo = { Name = "Halo"; Platform = "Xbox"; Score = None }

    let decideOn game =

        game.Score
        |> Option.map (fun score -> if score > 3 then "play it" else "don't play")

    //HINT: look at the return type of the decide on function
    AssertEquality (decideOn chronoTrigger) (Some "play it")
    AssertEquality (decideOn halo) (Some "don't play")

我得到的例外是:

You have not yet reached enlightenment ...
  Expected: null
  But was:  <Some(don't play)>

如何将字符串向上转换为option string类型?

1 个答案:

答案 0 :(得分:3)

  

如何将字符串向上转换为选项字符串类型?

施法具有非常特殊的含义。您要做的是用string包裹Option,而不是投射它。为此,请使用Some构造函数:

let x = Some myString //x: string option

但是,我认为这不会解决你得到的断言错误(至少不是自己)。我不想在这里给你完整的答案(特别是因为那不是你所要求的,找到答案就是做Koan的全部意义)但我会留下这个线索作为为什么你在断言中看到null

None |> printfn "Value: %A" // Value: <null>

有关该行为的更多信息,请参阅Why is None represented as null?