简体   繁体   中英

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. 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.

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 );;

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. 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 . Maybe an if statement would work? 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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