【问题标题】:OCaml: applying second argument first(higher-order functions)OCaml:首先应用第二个参数(高阶函数)
【发布时间】:2014-06-07 08:01:25
【问题描述】:

我这样定义了一个高阶函数:

val func : int -> string -> unit

我想通过两种方式使用这个功能:

other_func (func 5)
some_other_func (fun x -> func x "abc")

即,通过使用已定义的参数之一创建函数。但是,第二种用法不如第一种用法简洁易读。有没有更易读的方法来传递第二个参数来创建另一个函数?

【问题讨论】:

  • other_funcsome_other_func 是高阶函数(它们对其他函数进行操作),而不是 func

标签: functional-programming ocaml readability higher-order-functions


【解决方案1】:

标题“参数更改顺序”中提出的问题已经得到解答。但是我将您的描述读作“如何编写一个固定第二个参数的新函数”。所以我会用一个 ocaml 顶层协议来回答这个简单的问题:

# let func i s = if i < 1 then print_endline "Counter error."
    else for ix = 1 to i do print_endline s done;;
val func : int -> string -> unit = <fun>
# func 3 "hi";;
hi
hi
hi
- : unit = ()
# let f1 n = func n "curried second param";;
val f1 : int -> unit = <fun>
# f1 4;;
curried second param
curried second param
curried second param
curried second param
- : unit = ()
# 

【讨论】:

    【解决方案2】:

    在 Haskell 中,有一个函数 flip 用于此。你可以自己定义:

    let flip f x y = f y x
    

    那么你可以说:

    other_func (func 5)
    third_func (flip func "abc")
    

    Flip 在 Jane Street Core 中定义为 Fn.flip。它在 OCaml Batteries Included 中定义为 BatPervasives.flip。 (换句话说,每个人都同意这是一个有用的功能。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 2015-06-25
      • 2010-12-31
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多