【问题标题】:Why are implicit parameters not considered compiler errors in F#为什么隐式参数在 F# 中不被视为编译器错误
【发布时间】:2015-05-02 11:03:39
【问题描述】:

我对函数式编程有点陌生,虽然我对 F# 有点熟悉,但我仍在学习它所有奇怪的工作方式。

//I love my Rice and Curry'd functions

let add x  = 
   let subFunction y = 
      x + y                   
   subFunction    

//explicit parameter
let add1 y = add 1 y

//implicit parameter 
let add10 = add 10

//calling it with the parameter it doesn't show that it takes
let twenty = add10 10

所以这里 add10 具有隐式参数,因为它调用一个函数,该函数返回一个带参数的函数。为什么我可以这样声明它而不是我声明 add1 的方式被接受?

从它的声明来看,它确实具有欺骗性,人们会认为它只是一个 int。

【问题讨论】:

    标签: f# functional-programming currying


    【解决方案1】:

    这是来自 lambda 演算的东西,称为 eta-reduction

    基本上这意味着您可以通过在表达式两侧相同的情况下消除最后一个参数来简化您的函数/lambda:

    // instead of
    let f x y = x + y
    
    // in F# you can write
    let f x y = (+) x y
    
    // which is also the same as
    let f x y = ((+) x) y
    
    // then you can remove y
    let f x   = (+) x
    
    // and then remove x
    let f     = (+)
    

    在 F# 中,只要您没有到达 value restriction,您就可以使用它。所以在你的代码中 let add1 y = add 1 ylet add10 = add 10 是等价的。这是一个示例,说明如何将逻辑应用于代码推理,应用于重构。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多