Omer Gafla
Omer Gafla

Reputation: 46

ML programming language - Curry Function

I need to find a function with the signature of:

'a -> 'b -> ('a * 'b -> 'b) -> 'b

So i tried to do it like this:

fun f a b g = g(a,b)

and got the result:

val f = fn : 'a -> 'b -> ('a * 'b -> 'c) -> 'c

How can I set this c to a b as required?

Thank you very much.

Upvotes: 2

Views: 121

Answers (2)

molbdnilo
molbdnilo

Reputation: 66459

The problem is that g(a,b) does not restrict the resulting type.

The only value of type 'b that you have access to is the second argument, so you need to return that somewhere, or use it to somehow restrict the result.

A very simple solution is to add a condition,

- fun f a b g = if false then b else g(a,b);
val f = fn : 'a -> 'b -> ('a * 'b -> 'b) -> 'b

Addendum, weeks later, as I suddenly remembered a more elegant solution, without the ugly conditional.
Since g's result should have the same type as its second argument, you can feed it its own result.
This will force b and g(a,b) to have the same type:

- fun f a b g = g(a, g(a,b));
val f = fn : 'a -> 'b -> ('a * 'b -> 'b) -> 'b

Upvotes: 3

Maëlan
Maëlan

Reputation: 4202

You can write an explicit type annotation, for instance:

fun f a b (g : _ * 'b -> 'b) = g(a,b)
(* val f = fn : 'a -> 'b -> ('a * 'b -> 'b) -> 'b *)

The inferred type 'a -> 'b -> ('a * 'b -> 'c) -> 'c is strictly more general than the type 'a -> 'b -> ('a * 'b -> 'b) -> 'b you impose.

On type annotations for functions, see also this question.

Upvotes: 2

Related Questions