Skip to content

Instantly share code, notes, and snippets.

@miniBill
Created October 30, 2024 00:47
Show Gist options
  • Save miniBill/113a8c97e36ced7248405e62ab2fc269 to your computer and use it in GitHub Desktop.
Save miniBill/113a8c97e36ced7248405e62ab2fc269 to your computer and use it in GitHub Desktop.
toFraction : Float -> String
toFraction f =
let
below =
floor f
above =
ceiling f
go budget ln ld un ud =
let
mn =
ln + un
md =
ld + ud
mid =
toFloat mn / toFloat md
in
if budget <= 0 || mid == f then
let
g =
gcd (abs mn) (abs md)
gcd a b =
if a < b then
gcd b a
else if b == 0 then
a
else
gcd (modBy b a) b
in
if md // g == 1 then
String.fromInt (mn // g)
else
String.fromInt (mn // g) ++ "/" ++ String.fromInt (md // g)
else if f < mid then
go (budget - 1) ln ld mn md
else
go (budget - 1) mn md un ud
in
go 100 below 1 above 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment