views:

62

answers:

1

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

+5  A: 

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) 
nlucaroni
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?
nicotine
Function returns function. HOF!
ygrek
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.
Pascal Cuoq
@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).
nlucaroni