OCaml递归函数将函数应用n次 [英] OCaml recursive function to apply a function n times
问题描述
我想在OCaml中创建一个类型为int - >('a - >'a) - >'a - >'的函数,该函数接受一个int n(非负)和一个函数f'a - > 'a和类型'a的争论。 f应该被调用一次。
I want to create a function of type int -> ('a -> 'a) -> 'a -> 'a in OCaml that takes an int n (non-neg) and a function f 'a -> 'a and an argument a of type 'a. f should be called on a n times.
我尝试了3种不同的东西,但只能得到int - >('a - >'b) - >'a - >'b,这里有一些我已经尝试过的。
I've tried 3 different things but can only get int -> ('a -> 'b) -> 'a -> 'b, here are a few things I've tried.
let rec f n g a =
g a;
f (n-1) g a;;
其中给出
which gives
val f : int -> ('a -> 'b) -> 'a -> 'c = <fun>
我试过了
and I've tried
let rec f n g a =
if n > 0 then f (n-1) g a
else g a
;;
这给了我
which gave me
val f : int -> ('a -> 'b) -> 'a -> 'b = <fun>
第二个更接近,但我对如何得到int - >('a - >'a) - >'a - >'a
The second is closer but I'm at a loss for how to get int -> ('a -> 'a) -> 'a -> 'a
推荐答案
我不太清楚您想要的内容做。我想这是下面的函数:
I'm not quite sure about what you are trying to do. I guess it is the function below:
let rec foldi i f acc =
if i <= 0 then acc else foldi (pred i) f (f acc)
递归地应用 i 将函数
f
乘以一个值 acc
,然后计算其结果。 foldi
可能不是最好的名字。
which recursively apply i
times the function f
to a value acc
and then to its its result. foldi
might not be the best name for it though.
这篇关于OCaml递归函数将函数应用n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!