Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
f2b43c23ce
|
28
src/fr.gleam
28
src/fr.gleam
@@ -3,6 +3,7 @@ import gleam/list
|
||||
import gleam/order
|
||||
import internal/utils
|
||||
|
||||
/// A number type represented as a fraction of two integers
|
||||
pub type Fr {
|
||||
Fr(n: Int, d: Int)
|
||||
}
|
||||
@@ -25,7 +26,8 @@ pub fn int(n) {
|
||||
Fr(n, 1)
|
||||
}
|
||||
|
||||
pub fn to_string(a: Fr) {
|
||||
/// Stringifies the number as a fraction
|
||||
pub fn to_frac_string(a: Fr) {
|
||||
let a = a |> norm
|
||||
let n = a.n |> int.to_string
|
||||
let d = a.d |> int.to_string
|
||||
@@ -36,11 +38,19 @@ pub fn to_string(a: Fr) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalizes the fraction to the simplest possible form
|
||||
pub fn norm(a: Fr) {
|
||||
// protect from zero division
|
||||
let a = case a.d {
|
||||
0 -> zero
|
||||
_ -> a
|
||||
}
|
||||
// only allow minus sign in the numerator
|
||||
let a = case a.d > 0 {
|
||||
True -> a
|
||||
False -> Fr(-a.n, -a.d)
|
||||
}
|
||||
// reduce the fraction if possible
|
||||
case utils.gcd(a.n, a.d) {
|
||||
1 -> a
|
||||
gcd -> Fr(a.n / gcd, a.d / gcd)
|
||||
@@ -60,14 +70,26 @@ pub fn add(a: Fr, b: Fr) {
|
||||
Fr(cd / a.d * a.n + cd / b.d * b.n, cd) |> norm
|
||||
}
|
||||
|
||||
pub fn add_int(a: Fr, b: Int) {
|
||||
a |> add(int(b))
|
||||
}
|
||||
|
||||
pub fn sub(a: Fr, b: Fr) {
|
||||
b |> neg |> add(a)
|
||||
}
|
||||
|
||||
pub fn sub_int(a: Fr, b: Int) {
|
||||
a |> sub(int(b))
|
||||
}
|
||||
|
||||
pub fn mul(a: Fr, b: Fr) {
|
||||
Fr(a.n * b.n, a.d * b.d) |> norm
|
||||
}
|
||||
|
||||
pub fn mul_int(a: Fr, b: Int) {
|
||||
a |> mul(int(b))
|
||||
}
|
||||
|
||||
pub fn div(a: Fr, b: Fr) {
|
||||
case b.n {
|
||||
0 -> int(0)
|
||||
@@ -75,6 +97,10 @@ pub fn div(a: Fr, b: Fr) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn div_int(a: Fr, b: Int) {
|
||||
a |> div(int(b))
|
||||
}
|
||||
|
||||
pub fn sum(l: List(Fr)) {
|
||||
list.fold(l, zero, add)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// fr fr
|
||||
import fr.{Fr}
|
||||
import fr
|
||||
import gleam/io
|
||||
|
||||
pub fn main() {
|
||||
fr.pi
|
||||
|> fr.to_string
|
||||
|> fr.to_frac_string
|
||||
|> io.println
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user