I am trying to remove an element from a doubly-linked list based on wether a node in that list satisfies a function that returns a bool. For some reason the previous pointer of the replacing node (next of removed) does not update and instead refers back to itself.
My Code
(* The type of linked lists. *)
type 'a llist =
| Nil
| Cons of (float * 'a) * 'a lcell * 'a lcell
and 'a lcell = ('a llist) ref
let remove p head =
let rec remove' ll =
match !ll with
|Nil -> head := !head (*no node match*)
|Cons ((a, _), c, d) ->
if p a then
match (!c, !d) with
|(Nil, Nil) -> head := ref Nil (*singleton match*)
|(Cons(_, c', d'), Nil) -> (*last node match*)
d' := Nil
|(Nil, Cons(_, c', d')) -> (*first node match*)
head := d;
c':= Nil
|(Cons(_, _, d'), Cons(_, e', _))-> (*middle match; Does not work*)
e' := !c;
d' := !d
else
remove' d
in
remove' !head
Test Results
Initial value of head is
{contents =
@1:{contents =
Cons ((-1.689, 3),
@2:{contents = Nil},
@3:{contents =
Cons ((0.910, -1),
<@1>,
@4:{contents =
Cons ((0.647, 3),
<@3>,
@5:{contents =
Cons ((4.531, -1),
<@4>,
@6:{contents = Nil})})})})}}
Calling remove (fun x -> close x 0.646639313413) head (*close compares values accuracy up to two decimal digits*)
The value of head is now
{contents =
@1:{contents =
Cons ((-1.689, 3),
@2:{contents = Nil},
@3:{contents =
Cons ((0.910, -1),
<@1>,
@4:{contents =
Cons ((4.531, -1), <@4>, @5:{contents = Nil})})})}}