Facebook
From Hot Shama, 1 Year ago, written in OCaml (Objective Caml).
This paste is a reply to Untitled from Ivory Earthworm - view diff
Embed
Download Paste or View Raw
Hits: 328
  1. module type Container =
  2. sig
  3.         type 'a t
  4.         exception Empty of string
  5.         exception Full of string
  6.        
  7.         val create: unit -> 'a t
  8.         val put: 'a * 'a t -> unit
  9.         val take: 'a t -> 'a
  10. end;;
  11.  
  12. module ContainerOption =
  13. struct
  14.                 type 'a t = { mutable a : 'a option }
  15.                 exception Empty of string
  16.                 exception Full of string
  17.                
  18.                 let create() = { a = None }
  19.                
  20.                 let put (e, c) =
  21.                         match c.a with
  22.                         | None -> (c.a <- Some e)
  23.                         | _ -> raise(Full "f")
  24.                
  25.           let take c =
  26.                         match c.a with
  27.                         | None -> raise(Empty "e")
  28.                         | Some e -> begin c.a <- None; e end
  29. end;;
  30.  
  31. let cO = ContainerOption.create();;
  32. ContainerOption.put(1, cO);;
  33. ContainerOption.take cO;;
  34.  
  35.  
  36. module ContainerList =
  37. struct
  38.         type 'a t = { mutable n : int; mutable a : 'a list }
  39.         exception Empty of string
  40.         exception Full of string
  41.        
  42.         let create() = { n = 0; a = [] }
  43.        
  44.         let put (e, c) =
  45.                 match c.n with
  46.                 | 0 -> begin    c.a <- [e]; c.n <- c.n + 1 end
  47.                 | _ -> raise (Full "f")
  48.        
  49.         let take c =
  50.                 match c.n with
  51.                 | 0 -> raise (Empty "e")
  52.                 | _ -> begin c.n <- c.n - 1; c.a end
  53.  
  54. end;;
  55.  
  56. let cL = ContainerList.create();;
  57. ContainerList.put(1, cL);;
  58. ContainerList.take cL;;