Let's start with our code from last time:
type point = float * float
type shape =
(* lets represent a circle by it's center and it's radius*)
(* we can use the "of" keyword to make it carry more data*)
| Circle of {center: point; radius: float}
(* let's represent rectangles with their lower left
coordinate and their upper right coordiante.*)
| Rectangle of {lower_left: point; upper_right: point}
let c1 = Circle {center = (0., 0.); radius = 1.}
let r1 = Rectangle {lower_left = (-1., -1.); upper_right = (1., 1.)}
type point = float * float
type shape =
Circle of { center : point; radius : float; }
| Rectangle of { lower_left : point; upper_right : point; }
val c1 : shape = Circle {center = (0., 0.); radius = 1.}
val r1 : shape = Rectangle {lower_left = (-1., -1.); upper_right = (1., 1.)}
What if we want to find the center of our shape? We can use pattern matching!
let center s =
match s with
| Circle {center; radius} -> center
(* it's going to be easier if we have an average function. Let's come back to this*)
| Rectangle {lower_left; upper_right} -> failwith "Unimplemented"
val center : shape -> point = <fun>
let avg a b = (a +. b) /. 2.;;
val avg : float -> float -> float = <fun>
let center s =
match s with
| Circle {center; radius} -> center
| Rectangle {lower_left; upper_right} ->
let (x_ll, y_ll) = lower_left in (* we can pattern match in let expressions *)
let (x_ur, y_ur) = upper_right in
(avg x_ll x_ur, avg y_ll y_ur)
val center : shape -> point = <fun>
Okay cool! Now let's test our center function.
center c1;;
center r1;;
- : point = (0., 0.)
- : point = (0., 0.)
Both of our shapes are centered at the origin.