I am trying to define a new type of data, to create a list and then to create a stream out of the list:
type 'a myType = Name of char ;;
let myList = [Name('a')];;
let myStream = Stream.of_list myList;;
Error: The type of this expression, ‘_a myType Stream.t,
contains type variables that cannot be generalized
Any idea?
In your code,
myStreamis a stream of typemyTypeparametrized by an unknown type (which is called'_ain your error above). The compiler did not find enough information in your code about what'_ashould be.In some cases, the compiler would then generalize the type by stating that
'_acan be anything. For instance,myListis properly identified as'a myType list. However, given thatStream.tis an abstract type, generalization might cause errors, so it is not performed.One way to work around this is to specify the type of
'_aif you only intend it to be used with a single type, for instance with a type constraint :Another way, if you wish to keep it generic, is to turn it into a function (which is then automatically generalized) :
The type will be
unit -> 'a myType Stream.tas expected.The underlying reason why such generalization might cause errors is the presence of mutable state. Suppose that I define four files as such:
This would cause a runtime error. As such, whenever mutable state is involved, types cannot be generalized.