简体   繁体   English

以函数作为参数定义函数

[英]Defining a function with a function as an argument

I am currently trying to define a function of type ('a -> 'a) -> 'a -> 'a which takes a function of type 'a -> 'a and an argument of type 'a and calls the function twice on the argument. 我目前正在尝试定义类型为('a->'a)->'a->'a的函数,该函数接受类型为'a->'a的函数和类型为'a的参数,并两次调用该函数论据。 I'm relatively new to OCaml but I do know how to define a function, but I had no luck with trial and error or Google trying to get a function to take a function as an argument and then apply that function twice. 我是OCaml的新手,但我确实知道如何定义函数,但是我对试错法或Google尝试获取函数以将函数作为参数然后两次应用该函数并不满意。

Any tips or pointers would be greatly appreciated, thanks in advance. 任何提示或指示,将不胜感激,在此先感谢。

edit: Thanks to Jeffrey below, my problem is now solved. 编辑:感谢下面的杰弗里,我的问题现在已经解决。

let f4 ga = g (ga );; 令f4 ga = g(ga);;

val f4 : ('a -> 'a) -> 'a -> 'a = val f4:('a->'a)->'a->'a =

OCaml infers types, so if you use an argument as a function, it infers that it's a function. OCaml会推断类型,因此,如果将参数用作函数,则会推断它是一个函数。 Here's an example: 这是一个例子:

# let f g = g 8 + g 10;;
val f : (int -> int) -> int = <fun>
# (~-);;
- : int -> int = <fun>
# f (~-);;
- : int = -18

To understand the example, note that (~-) is the ordinary integer negation operator. 要理解该示例,请注意(~-)是普通的整数求反运算符。

Update : A hint for your more complicated problem. 更新 :有关您更复杂问题的提示。 You need to test the value of n . 您需要测试 n的值。 Maybe an if statement would work? 也许if语句会起作用? Second hint: if you use recursion, you don't need to use a loop. 第二个提示:如果使用递归,则不需要使用循环。 If you want to use a loop, don't use recursion. 如果要使用循环,请不要使用递归。 (Personally I'd suggest using recursion, it's like playing scales while learning piano.) (我个人建议使用递归,这就像在学习钢琴时弹奏音阶。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM