1
votes

I'm trying to write a SML function that has two argument, the first is an int and the second is a list of lists. The objective is to insert the first argument onto the front of every list in the second arguemnt. For example, append_to_front(1,[[3,4],[6,8],[]]) should return [[1,3,4],[1,6,8],[1]].

I have the code:

fun append_to_front(a:int, L:int list list) =
    if L = []
    then []
    else a::hd(L)::append_to_front(a, tl(L));

and I get the error message: Error: operator and operand don't agree [tycon mismatch]. Why?

1
You can also solve this with a higher-order function: fun append_to_front (x, L) = map (fn xs => x::xs) LSimon Shine

1 Answers

4
votes

The cons operator :: has type 'a * 'a list -> 'a list, that is, it requires an element on the left and a list on the right. Moreover, it is right-associative, i.e., a::b::c = a::(b::c).

In your case, a has type int, b and c both have type int list. Consequently, the second use of :: isn't well-typed, because it has a list on both sides. Use list concatenation @ in that place instead.