Skip to content

Instantly share code, notes, and snippets.

@cohama
Created April 15, 2013 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cohama/5388295 to your computer and use it in GitHub Desktop.
Save cohama/5388295 to your computer and use it in GitHub Desktop.
structure
module type PRIOQUEUE =
sig
type priority = int
type 'a queue
val empty : 'a queue
val insert : 'a queue -> int -> 'a -> 'a queue
val extract : 'a queue -> int * 'a * 'a queue
exception Queue_is_empty
end;;
module PrioQueue =
struct
type priority = int
type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue
let empty = Empty
let rec insert queue prio elt =
match queue with
| Empty -> Node(prio, elt, Empty, Empty)
| Node(p, e, left, right) ->
if prio <= p
then Node(prio, elt, insert right p e, left)
else Node(p, e, insert right prio elt, left)
exception Queue_is_empty
let rec remove_top = function
| Empty -> raise Queue_is_empty
| Node(_, _, left, Empty) -> left
| Node(_, _, Empty, right) -> right
| Node(_, _, (Node(lprio, lelt, _, _) as left),
(Node(rprio, relt, _, _) as right)) ->
if lprio <= rprio
then Node(lprio, lelt, remove_top left, right)
else Node(rprio, relt, left, remove_top right)
let extract = function
| Empty -> raise Queue_is_empty
| Node(prio, elt, _, _) as queue -> (prio, elt, remove_top queue)
end;;
PrioQueue.insert PrioQueue.empty 1 "hello";;
module AbstPrioQueue = (PrioQueue : PRIOQUEUE);;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment