Money_refactored
unknown
ocaml
10 months ago
1.6 kB
23
Indexable
module Money : sig
type t [@@deriving show]
type currency_symbol [@@deriving show]
type currency [@@deriving show]
val make : ?currency:currency -> int -> t
val add : t -> t -> t
val multiply : t -> int -> t
val amount : t -> int
val equals : t -> t -> bool
end = struct
type currency_symbol = [ `USD | `EUR ] [@@deriving show]
type currency = { divisor : int; symbol : currency_symbol; desc : string }
[@@deriving show]
type t = { amount : int; currency : currency } [@@deriving show]
let validate_same_currency t1 t2 =
if t1.currency.symbol <> t2.currency.symbol then
failwith "Currencies do not match"
let compare t1 t2 =
validate_same_currency t1 t2;
Int.compare t1.amount t2.amount
let default_currency =
{ divisor = 100; symbol = `USD; desc = "United States Dollar" }
let make ?(currency = default_currency) amount = { amount; currency }
let equals t1 t2 = compare t1 t2 = 0
let add t1 t2 =
validate_same_currency t1 t2;
{ t1 with amount = t1.amount + t2.amount }
let multiply t n = { t with amount = t.amount * n }
let amount t1 = t1.amount
end
let () =
let mon = Money.make 10 in
let mon2 = Money.make 20 in
let mon3 = Money.add mon mon2 in
Printf.printf "%d + %d = %s \n" (Money.amount mon) (Money.amount mon2)
(Money.show mon3);
let mon3 = Money.multiply mon 2 in
Printf.printf "%d * 2 = %s\n" (Money.amount mon) (Money.show mon3);
if Money.equals mon mon2 then
Printf.printf "%d %d Equal\n" (Money.amount mon) (Money.amount mon2)
else Printf.printf "%d %d Not Equal\n" (Money.amount mon) (Money.amount mon2)
Editor is loading...
Leave a Comment