user9361362
user9361362

Reputation:

SML: Inputting an empty list into function gives error "Warning: type vars not generalized because of value restriction..."

My function is meant to place the first item in the list at the end of the list. The list may be of any type. I tried to anticipate an empty list input but I get error regarding types.

What can I do to have this code work as intended?

fun cycle1 aList = if null(aList) then []else tl(aList) @ [hd aList];
cycle1 [];

stdIn:24.1-24.10 Warning: type vars not generalized because of
   value restriction are instantiated to dummy types (X1,X2,...)

Upvotes: 0

Views: 476

Answers (1)

molbdnilo
molbdnilo

Reputation: 66451

It's not an error, just a warning.

- fun cycle1 aList = if null(aList) then []else tl(aList) @ [hd aList];
val cycle1 = fn : 'a list -> 'a list
- cycle1 [];
stdIn:2.1-2.10 Warning: type vars not generalized because of
   value restriction are instantiated to dummy types (X1,X2,...)
val it = [] : ?.X1 list

Note that there actually is a result - [] - which is a list of a "dummy type", ?.X1 list.

This happens because a value can't be polymorphic (you can't create an 'a list).
Search for the value restriction for details.

You can avoid the warning by using the empty list of a specific type:

- cycle1 ([] :int list);
val it = [] : int list
- cycle1 ([] : string list);
val it = [] : string list

On a side note, I would recommend that you get familiar with pattern matching as soon as possible, as it makes code much more readable;

fun cycle1 [] = []
  | cycle1 (x::xs) = xs @ [x]

Upvotes: 1

Related Questions