Conversion of Lists to Linked Lists
I'm trying to convert a list to a singly linked list (not sure if doubly linked lists are possible anyway) in standard ML. However, I am not sure how this is done, but will show my attempt so far.
datatype 'a mlist = Nil
| Cons of 'a * 'a mlist ref
fun listToLL [] = Nil
| listToLL (x::xs) = Cons(x, (ref (listToLL xs)))
I have created a linked list over datatype first, but I'm confused by the 'ref' function. I want to avoid making the linked list into a lazy list, so the ref is there for me to explicitly make the next sequence a reference of the previous one only. But the problem is that this function does not make use of the linked list data type at all, and works even if I don't use this linked list definition. So is my implementation actually correct?
As a side question, is the only thing distinguishing linked lists from lazy lists the 'ref' function? Judging from their datatype definitions, this seem to be that way.
Joining two linked lists together
fun joining (mlpx, mlpy) =
case !mlpx of
Nil => mlpx := mlpy
| Cons(_, mlp) => joining(mlp, mlpy)
fun join (mlpx, mlpy) =
let
val mlp = ref mlpx
in
joining(mlp, mlpy);
!mlp
end;
For the second operation, I'm very confused by the need for ref
in the second join function at all. When I handle a linked list, do I expect that I handle a reference or do I handle the entire Cons structure that contains the reference from within? I don't get why we can't just use the joining
function by itself as it seems to be really sufficient. Why is there a need to create a ref
in the join
function?