I want to make a function for a new datatype in Standard ML, the datatype is called intnest, defined as the following:
datatype intnest =
INT of int
| LIST of intnest list;
and I want to make a function that adds all the integers in the intlist, I tried the following code:
fun addup (INT n) = n
| addup (LIST x::xs) = x + addup(xs);
What am I doing wrong?
EDIT:
I also tried the following:
fun addup (INT n) = n
| addup (LIST x::xs) = addup(x) + addup(xs);
so that x is of type INT so the first option returns its int value and the addup(xs) is a recursive call to return the same second option.
Also tried the following:
fun addup (INT n) = n
| addup (LIST []) = 0
| addup (LIST x::xs) = addup(x) + addup(LIST xs);
but I get the following error:
stdIn:146.4-151.50 Error: parameter or result constraints of clauses don't agree [tycon mismatch]
this clause: intnest list -> 'Z
previous clauses: intnest -> 'Z
in declaration:
addup =
(fn INT n => n
| LIST nil => 0
| :: (<pat>,<pat>) => addup <exp> + addup <exp>)
stdIn:151.25-151.50 Error: operator and operand don't agree [tycon mismatch]
operator domain: intnest
operand: intnest list
in expression:
addup x
First, there is a syntax error in the
LISTcase; get rid of theof. You’ll want the case to look likeaddup (LIST(x::xs)) = ....More substantially, there are conceptual problems in
addup. The desired type ofaddupappears to beintnest -> int. It’s thus necessary to ensure thataddupis always applied tointnestvalues and returningintvalues.Now consider the type of the elements of the list
x::xs. You defined it asLIST of intnest list, soxis anintnest. But inaddup, you treatxas an integer.Along the same lines,
xsis aintnest list, but that’s not anintnest, which is what you’re treating it as inaddup(xs). Your revised version addresses the problem withx, but not that withxs. You need to make anintnestfromxsusingLIST, which means you’ll need to useaddup(LIST xs).Finally, you are missing a case. What happens when you have
LIST []?The third version doesn’t work because you’re missing needed parentheses. The compiler is telling you that you’re using a
intnest listas one of the cases (the::case). That is, it seesLIST x::xsas(LIST x) :: xs.