Ocaml double linked list: remove a node satisfying a condition from a double linked list

Viewed 395

We have a double linked list defined as:

type 'a llist =
  | Nil
  | Cons of (float *'a) * 'a lcell * 'a lcell
and 'a lcell = ('a llist) ref

I have implemented an add head function as so:

let add_head x head = 
  match !(!head) with
  | Nil -> head := !(singleton x)
  | Cons (e, previous, next) -> 
      let temp = Cons (x, ref Nil, !head) in
      previous := temp;
      head := previous;; 

Note that to implement add head I used a singleton function

let singleton (init: float * 'a): 'a lcell ref =
  let l = ref (Cons (init, ref Nil, ref Nil)) in
  let front = ref l in
  front

My problem is when I try to remove an element, I am trying to write a remove function remove: (float -> bool) -> 'a lcell ref -> unit, such that remove p head removes the first node whose timestamp satisfies the predicate p: float -> bool. If no node's timestamp satisfies the predicate, the list should remain unchanged.

This is what I have so far:

let remove p head =
  let rec remove' ll =
    match !ll with 
    | Nil -> head := !head
    | Cons ( (d,_), previous, next) ->
        if p d then
          match (!previous, !next) with 
          | (Nil, Nil) -> head := ref Nil   (* empty list*)
          | (Nil, Cons ( d1, p1, n1)) -> (* this is the head, remove it and reassign head*)
              head := next; 
              p1 := Nil
          | (Cons ( d2, p2, n2), Cons ( d1, p1, n1)) -> (* this is middle, remove it and fix pointers of previous and next*)
              n2 := !next;
              p1 := !previous 
          | (Cons ( d1, p1, n1), Nil) -> (* this is tail, remove it and make previous one the tail*)
              n1:= Nil 
        else remove' next              
  in
  remove' !head

I am having trouble removing items in the in the middle of the list i.e not the head or the tail. I am also having trouble removing multiple elements. Can someone try to help me out, I think I'm missing something in my match cases.

1 Answers

You're messing up when you do cons cons in your match statement You have to replace previous and next and not n2 and p1 It should be

| Cons(d2, p2, n2), Cons (d1, p1, n1) ->
`previous := Cons(d2, p2, next);`
`next := Cons(d1, previous, n1);
Related