Skip to content

Instantly share code, notes, and snippets.

@bastih
Created November 27, 2012 12:49
Show Gist options
  • Save bastih/4154086 to your computer and use it in GitHub Desktop.
Save bastih/4154086 to your computer and use it in GitHub Desktop.
module ListPoint = struct
type point = int list
let make x y = [x; y]
let getX p = List.nth p 0
let getY p = List.nth p 1
let origin = [0; 0]
let print p = print_int (getX p); print_string " "; print_int (getY p); print_endline ""
end;;
module Square = struct
open ListPoint
type square = point * int
let opposite_point (p, length) = make ((getX p) + length) ((getY p) + length)
let make p length = (p, length) (* must be declared after opposite point, otherwise we can't use make from ListPoint *)
end;;
module AltSquare = struct
module LP = ListPoint
type square = LP.point * int
let make p length = (p, length)
let opposite_point (p, length) = (LP.make ((LP.getX p) + length) ((LP.getY p) + length))
end;;
module ExtendedSquare = struct
include Square
let area (_, length) = length * length
end;;
let my_point = ListPoint.make 10 20 in
let length = 30 in
let my_square = Square.make my_point length in
let opp = Square.opposite_point my_square in
let area = ExtendedSquare.area my_square in
ListPoint.print opp;
print_string "Area: "; print_int area; print_newline();
(* SIGNATURES and FUNCTORS *)
module type POINT_SIG = sig
type point
val make: int -> int -> point
val getX: point -> int
val getY: point -> int
val origin: point
val print: point -> unit
end;;
module ListPointWithSig : POINT_SIG = struct
type point = int list
let make x y = [x; y]
let getX p = List.nth p 0
let getY p = List.nth p 1
let origin = [0; 0]
let print p = print_int (getX p); print_string " "; print_int (getY p)
end;;
module TuplePointWithSig : POINT_SIG = struct
type point = int * int
let make x y = (x, y)
let getX (x, _) = x
let getY (_, y) = y
let origin = (0, 0)
let print (x, y) = print_int x; print_string " "; print_int y
end;;
module SquareFunctor(P: POINT_SIG) = struct
type square = P.point * int
let make p length = (p, length)
let opposite_point (p, length) = P.make ((P.getX p) + length) ((P.getY p) + length)
end;;
module TuplePointSquare = SquareFunctor(TuplePointWithSig);;
module ListPointSquare = SquareFunctor(ListPointWithSig);;
let my_point = TuplePointWithSig.make 10 20 in
let length = 10 in
let my_square = TuplePointSquare.make my_point length in
let opp = TuplePointSquare.opposite_point my_square in
TuplePointWithSig.print opp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment