I got some trouble with ocaml polymorphic function

Viewed 80

i need your help please, where is the error in my code ?

let create = Array.make_matrix 10 10;;

let assoc int = create int,create (char_of_int int);;

the error is

3 | let assoc int = create int,create (char_of_int int);;
                                      ^^^^^^^^^^^^^^^^^
Error: This expression has type char but an expression was expected of type
         int
2 Answers

when you define a polymorphic function implicitly on Ocaml, it has a `weak type meaning that a type will be definitely assigned to the function after you've called it once, so because you called to create on an int, it now has a type int -> int array and won't accept a char as an argument.

This is the "value restriction". You can make it work by defining create like this:

let create v = Array.make_matrix 10 10 v

It works like this:

# let create v = Array.make_matrix 10 10 v;;
val create : 'a -> 'a array array = <fun>

# let assoc int = create int,create (char_of_int int);;
val assoc : int -> int array array * char array array = <fun>

The value restriction states that only "values" (in a certain sense) can be polymorphic; in particular, an expression that just applies a function can't be fully polymorphic. You define create by just applying a function to some values, so the value restriction prevents it from being polymorphic. The above definition defines create instead as a lambda (a fun in OCaml), which is a "value" per the value restriction. So it can be fully polymorphic.

You can read about the value restriction in Chapter 5 of the OCaml manual.

Related