[back]

Freeing Memory

type mem_status =
  | Free
  | Occupied

type memory = (mem_status * int) list

This problem uses the same memory model as a previous problem. Recall that, in this model, memory is represented as a list of pairs, each representing a chunk of memory. The first entry of the pair determines whether the chunk is Free or Occupied, and the second determines how many units of memory the chunk occupies. Furthermore, we require that memory has the following properties:

In this problem, you'll be implementing memory freeing.

type free_result =
  | Success of memory
  | Invalid_position

Implement the function

val free : int -> memory -> free_result

so that free pos mem is a free_result such that:

Examples

let m0 = [(Free, 3); (Occupied, 1); (Occupied, 3); (Free, 2); (Occupied, 1)]
let _ = assert (free (-1) m0 = Invalid_position)
let _ = assert (free 1 m0 = Invalid_position) (* not the start of a chunk *)
let _ = assert (free 3 m0 =
                Success [(Free, 4); (Occupied, 3); (Free, 2); (Occupied, 1)])
let _ = assert (free 9 m0 =
                Success [(Free, 3); (Occupied, 1); (Occupied, 3)])
(* the trailing Free chunk is dropped, since memory is unlimited *)