I’m a little stuck on this assignment for OCAML. I’m trying to pass in a function and a value as a parameter into another function. For example, I have function called test that takes in (fun x -> x+x) and 3 as parameters. The function test should output 6, since 3 + 3 = 6. I know I can achieve something similar this by completing:
let func x = x + x;;
let a = func;;
let test a x = (a x);;
This way when I input, test a 5, I will get 10.
But when I change the statement to this, I get only the value I placed in for x. How do I get the (fun a -> a) to take in the value x?
let test a x = ((fun a -> a) x);;
fun a -> ais an anonymous identity function, it will always return its parameter. You could say:Note that in your
the first
aand the other twoas are different variables. The first one is never used again later. You can rewrite this line for easier understanding as:You are, and that’s the problem. You’re feeding your
xto an identity function, and gettingxback. What you want to do is feed thexto yourafunction, and that’s what you did in your first attempt: