Skip to content

Instantly share code, notes, and snippets.

@keleshev
Last active March 10, 2016 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keleshev/29a576d7cbd5f1f3822e to your computer and use it in GitHub Desktop.
Save keleshev/29a576d7cbd5f1f3822e to your computer and use it in GitHub Desktop.
open Core_kernel.Std
module QuadraticEquation = struct
open Float
type t = {a: float; b: float; c: float}
let discriminant {a; b; c} = b * b - 4.0 * a * c
let root {a; b; c} discriminant (+/-) =
(-1.0 * b +/- sqrt discriminant) / 2.0 * a
let solve ({a; b; c} as coefficients) =
let d = discriminant coefficients in
let root = root coefficients d in
match sign d with
| Sign.Neg -> `None
| Sign.Zero -> `One (root (+))
| Sign.Pos -> `Two (root (+), root (-))
end
let () =
let open QuadraticEquation in
assert (solve {a=1.0; b=(-1.0); c=(-2.0)} = `Two (2.0, -1.0));
assert (solve {a=1.0; b=(-6.0); c=9.0} = `One 3.0);
assert (solve {a=3.0; b=4.0; c=2.0} = `None);
print_endline "ok"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment