Guest User

Untitled

a guest
Nov 19th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.60 KB | None | 0 0
  1. open Batteries
  2.  
  3. class virtual number = object(self : 'a)
  4.   method virtual succ : 'a
  5.   method virtual pred : 'a option
  6. end
  7.  
  8.  
  9.  
  10. type lazy_number_data =
  11.   | Number of number
  12.   | Zero
  13.   | Succ of lazy_number_data
  14.   | Sum of lazy_number_data * lazy_number_data
  15.  
  16. class lazy_number data0 = object
  17.   inherit number
  18.   val data = data0
  19.   method succ = {< data = Succ data >}
  20.   method pred =
  21.     let rec aux = function
  22.       | Number x -> x#pred |> Option.map (fun t -> Number t)
  23.       | Zero -> None
  24.       | Succ x -> Some x
  25.       | Sum (x1, x2) -> begin
  26.           match aux x1 with
  27.           | None -> aux x2
  28.           | Some x1' -> Some (Sum (x1', x2))
  29.         end
  30.     in
  31.     match aux data with
  32.     | None -> None
  33.     | Some data' -> Some {< data = data' >}
  34. end
  35.  
  36. let lazy_sum x y =
  37.   let lazy_x = Number x in (* This could be x#data is x is an instance of lazy_number *)
  38.   let lazy_y = Number y in
  39.   new lazy_number (Sum (lazy_x, lazy_y))
  40.  
  41.  
  42.  
  43. type unary_number_data =
  44.   | O
  45.   | S of unary_number_data
  46.  
  47. class unary_number data0 = object
  48.   inherit number
  49.   val data = data0
  50.   method succ = {< data = S data >}
  51.   method pred =
  52.     match data with
  53.     | O -> None
  54.     | S data' -> Some {< data = data' >}
  55. end
  56.  
  57. let rec unary_number_of_number x =
  58.   match x#pred with
  59.   | None -> O
  60.   | Some x' -> S (unary_number_of_number x')
  61.                    
  62. let unazy_sum x0 y0 =
  63.   let unary_x = unary_number_of_number x0 in (* This could be x0#data if x0 is an instance of unary_number *)
  64.   let rec aux y =
  65.     match y#pred with
  66.     | None -> unary_x
  67.     | Some y' -> S (aux y')
  68.   in
  69.   aux y0
Add Comment
Please, Sign In to add comment