4

I have two functions f and g and I am trying to return f(g(x)) but I do not know the value of x and I am not really sure how to go about this.

A more concrete example: if I have functions f = x + 1 and g = x * 2 and I am trying to return f(g(x)) I should get a function equal to (x*2) + 1

1 Answer 1

5

It looks like you have it right, f(g(x)) should work fine. I'm not sure why you have a return keyword there (it's not a keyword in ocaml). Here is a correct version,

let compose f g x = f (g x) 

The type definition for this is,

val compose : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c = <fun> 

Each, 'a,'b,'c are abstract types; we don't care what they are, they just need to be consistent in the definition (so, the domain of g must be in the range of f).

let x_plus_x_plus_1 = compose (fun x -> x + 1) (fun x -> x * 2) 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much that helped a lot! But I have another question, how is it that we are allowed to call compose without specifying a value for x?
Function returns function. HOF!
Perhaps what is happening is clearer when writing it let compose f g = fun x -> f (g x) but these programs are exactly the same thing (one is syntactic sugar for the other, I am not sure which). Calling compose f g doesn't require a value for x because compose f g doesn't use x: it builds and returns a function.
@nicotine; Yes, it returns a functions that takes the newly defined types. In fact, this is the point of currying. So, for example, x_plus_x_plus_1 is a function of, (int -> int).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.