【问题标题】:F# dynamic operator with special left argument具有特殊左参数的 F# 动态运算符
【发布时间】:2021-07-05 13:22:42
【问题描述】:

在下面的 F# sn-p

let (?) (map : Map<string, string>) (key : string) = map.[key]

let map = [("aKey", "aValue"); ("another Key", "another Value")] |> Map.ofList

let a = map.["aKey"]
let b = map?aKey
assert (a = b)

let c = map.["another Key"] //OK
let d = map?another Key //How should this be written?
assert (c = d)

let d = map?... 行的正确语法是什么?

【问题讨论】:

    标签: dynamic f#


    【解决方案1】:

    F# 有特殊的运算符,使无效的标识符有效。 docs 中没有关于这个运算符的太多信息,甚至没有它的名字

    ``...``
    

    我称之为双反。它主要用于数据访问,例如

    // process CSV file with header "Production year,Make,Model"
    
    type Cars = CsvProvider<"file.csv">
    let sample = Cars.GetSample()
    for row in sample.Rows do
        row.``Production year`` |> printfn "%d"
    

    在您的示例中,您可以使用

    let d = map?``another key``
    

    C# 编译器为记录创建公共方法&lt;Clone&gt;$。它有这么奇怪的名字,所以没有人会尝试访问它,但我们可以从 F#

    let myRecord = ...;
    let copyOfRecords = myRecord.``<Clone>$``()
    

    Roslyn 团队故意试图隐藏这个成员,所以不要使用这个代码,只要知道这是可能的。

    【讨论】:

    • 我知道双反引号,只是没想到在这里使用它。
    【解决方案2】:

    我想这就是你想要的

    let (?) (map : Map<string, string>) (key : string) = map.[key]
    
    let map = [("aKey", "aValue"); ("another Key", "another Value")] |> Map.ofList
    
    let a = map.["aKey"]
    let b = map ? ("aKey") 
    let b = map?aKey // alternative, as you wrote it
    assert (a = b)
    
    let c = map.["another Key"] 
    let d = map ? ("another Key") // here the lexer requires " and even brackets
    assert (c = d)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2013-06-13
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多