Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.07 KB | None | 0 0
  1. (*
  2.  * queue.fs
  3.  * Author: Angel Rosario - 841127893
  4.  * Date: November 23, 2014
  5.  * Source (implementation) file for a generic queue.
  6.  * This is the implementation (source) file of the data structure Queue.
  7.  *)
  8.  
  9. // Indicates the namespace that contains the Queue module.
  10. namespace FunctionalCollections
  11.  
  12. // Defines the EmptyQueue exception.
  13. exception EmptyQueue of string
  14.  
  15.  
  16. // Declares the Queue module.
  17. module Queue =
  18.     // Declares the queue data type.
  19.     type 'a queue = QueueList of 'a list * 'a list
  20.  
  21.    // Returns a new empty queue.
  22.    let empty = QueueList([], [])
  23.  
  24.    // Determines whether a queue is empty.
  25.    let isEmpty = function
  26.        | QueueList([], []) -> true
  27.        |_ -> false
  28.  
  29.    // Adds an element to the front of a queue.
  30.    let add elem (QueueList (remElems, addElems)) = QueueList (remElems, elem::addElems)
  31.  
  32.    let rec fillLeftList (QueueList (remElems, addElems)) =
  33.        match remElems, addElems with
  34.        | _, [] -> QueueList (remElems, [])
  35.        | rem, hd::tail -> fillLeftList (QueueList (hd::rem, tail) )
  36.        
  37.  
  38.    // Removes the element at the front of a queue.
  39.    // Raises EmptyQueue exception if needed.      QueueList([1;2;3],[])
  40.    let rec remove = function
  41.        | QueueList([], []) -> raise (EmptyQueue "queue is empty")
  42.        | QueueList([], elems) -> remove (fillLeftList (QueueList([], elems)))
  43.        | QueueList(_::tl, elems) -> QueueList (tl, elems)
  44.        
  45.  
  46.    // Returns the element at the top of a queue.
  47.    // Raises EmptyQueue exception if needed.
  48.    let rec peek = function
  49.        | QueueList([], []) -> raise (EmptyQueue "queue is empty")
  50.        | QueueList([], elem) -> peek (fillLeftList (QueueList([], elem)))
  51.        | QueueList (hd::_,_) -> hd
  52.  
  53.    // Iterates through a queue using a visit function.
  54.    let rec iter visit = function
  55.        | QueueList ([],[]) -> ()
  56.        | QueueList ([], elems) -> iter visit (fillLeftList (QueueList ([], elems)))
  57.        | QueueList (hd::tl, elems) -> visit hd
  58.                                       iter visit (QueueList (tl, elems))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement