Reputation: 87
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.
val f4 : ('a -> 'a) -> 'a -> 'a =
Upvotes: 0
Views: 118
Reputation: 66823
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.)
Upvotes: 1