【问题标题】:Higher order function in F#F# 中的高阶函数
【发布时间】:2023-03-18 18:46:01
【问题描述】:

大家好,我想表达对 test1 的函数调用,而不是先定义更高的函数

let higher = fun a b -> a>b
let rec test1 test2 number list=

        match (number,list) with
        |number,[]                           -> []
        |number,x1::xs when test2 a x = true -> x1::test1 test2 number xs 
        |number,x1::xs                       -> test1 test2 number xs 

printfn "%A" (test1 (higher 5 [5;2;7;8]))

【问题讨论】:

  • if a > b then true else false 可以更简洁地写成a > b
  • 是的,这就是本地绑定的工作方式。它们是本地的,而不是全局的。

标签: lambda f# functional-programming


【解决方案1】:

这是设计使然。在函数内定义的值和函数只能在该函数内访问,它们在外部不可见。

这允许我们在不污染全局命名空间的情况下定义辅助函数和中间值。

要使函数higher 可以在函数test1 之外访问,您需要在test1 之前或之后定义它,而不是在它内部。在test1 中定义的任何内容都只能在test1 中访问。

【讨论】:

    【解决方案2】:

    如果您不想定义 higher 而是将函数传递给具有相同作用的 test1,则只需传递函数字面量:

    printfn "%A" (test1 ((fun a b -> a > b) 5 [5;2;7;8]))
    

    或者,因为在这种情况下,您只是直接比较两个操作数,甚至更短:

    printfn "%A" (test1 ((>) 5 [5;2;7;8]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      相关资源
      最近更新 更多