MODULE listExamples; FROM InOut IMPORT WriteString,WriteInt,WriteLn; FROM lists2 (* elller lists1 *) IMPORT List,null,hd,tl,cons,nil,changeTl; (* SML fun length l = if null l then 0 else 1+length(tl l) *) PROCEDURE length1(l:List):CARDINAL; (* length1 ger längden på listan l. Rekursiv lösning. *) BEGIN IF null(l) THEN RETURN 0 ELSE RETURN 1+length1(tl(l)) END END length1; PROCEDURE length2(l:List):CARDINAL; (* length2 ger längden på listan l. Iterativ lösning. *) VAR i:List; len:CARDINAL; BEGIN i:=l; len:=0; WHILE NOT null(i) DO i:=tl(i); INC(len) END; RETURN len END length2; PROCEDURE fromto(from,to:INTEGER):List; (* fromto(a,b) ger listan [a,a+1,...,b] *) BEGIN IF from<=to THEN RETURN cons(from,fromto(from+1,to)) ELSE RETURN nil() END END fromto; (* SML fun squareList [] = [] | squareList (x::xs) = x*x :: squareList xs *) PROCEDURE squareList(l:List):List; (* squareList kvadrerar alla elementen i en heltalslista. *) BEGIN IF null(l) THEN RETURN nil() ELSE RETURN cons(hd(l)*hd(l), squareList(tl(l))) END END squareList; PROCEDURE WriteList(l:List); BEGIN IF null(l) THEN WriteString("nil") ELSE WriteInt(hd(l),1); WriteString("::"); WriteList(tl(l)) END END WriteList; PROCEDURE insert1(x:INTEGER; xs:List):List; (* sätter in ett tal på rätt plats i en sorterad lista. Icke destruktiv. *) BEGIN IF null(xs) OR (x<=hd(xs)) THEN RETURN cons(x,xs) ELSE RETURN cons(hd(xs),insert1(x,tl(xs))) END END insert1; PROCEDURE insert2(x:INTEGER; xs:List):List; (* sätter in ett tal på rätt plats i en sorterad lista. Destruktiv. *) BEGIN IF null(xs) OR (x<=hd(xs)) THEN RETURN cons(x,xs) ELSE changeTl(xs,insert2(x,tl(xs))); RETURN xs END END insert2; BEGIN WriteList(insert1(7,squareList(fromto(1,5)))); WriteLn END listExamples.