F#:像应用函数一样应用值

时间:2019-06-03 17:15:18

标签: function functional-programming f#

在F#中是否可以像应用函数一样应用值?例如:

let record =
    {|
        Func = fun x -> x * x
        Message = "hello"
    |}
let message = record.Message   // unsweetened field access
let unsweet = record.Func 3    // unsweetened function application
let sweet = record 3           // sweetened function application

现在,最后一行当然不会编译:

error FS0003: This value is not a function and cannot be applied.

是否存在某种语法上的甜味剂,可以让我按照我认为合适的方式“路由”功能应用程序,同时仍然保留其正常的不加糖的行为?我在想这样的魔术:

// magically apply a record as though it was a function
let () record arg =
    record.Func arg

(注意:在本示例中,我使用了一条记录,但我也会对一个类感到满意。)

1 个答案:

答案 0 :(得分:2)

我能想到的最接近的东西是使用静态解析的类型参数来解析类型FSharpFunc的特定属性的自定义运算符,然后使用提供的输入参数调用该函数。像这样:

let record =
    {|
        Func = fun x -> x * x
        Message = "hello"
    |}

let inline (>.>) (r: ^a) v = 
    let f = (^a : (member Func: FSharpFunc< ^b, ^c>) r)    
    f v

record >.> 3 // val it : int = 9
相关问题