Skip to content

Commit

Permalink
Add fromfrac function for converting fractions to dividable types
Browse files Browse the repository at this point in the history
  • Loading branch information
Izaakwltn authored and stylewarning committed Oct 16, 2024
1 parent b5e8693 commit 7fc91f8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
10 changes: 10 additions & 0 deletions docs/intro-to-coalton.md
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,16 @@ All of these cases are sufficiently common that we provide a few shorthands:

- `floor/`, `ceiling/`, and `round/` for integer-to-integer division, and

Fractions can be converted to other dividable types using `fromfrac` (Note: This may result in precision loss):

```
COALTON-LIBRARY/MATH/REAL> (coalton (the Double-Float (fromfrac 1/2)))
0.5d0
COALTON-LIBRARY/MATH/REAL> (coalton (the Single-Float (fromfrac 999/1000)))
0.999
```


## Lists

Coalton uses Lisp lists under the hood. Lists can be constructed with `make-list`.
Expand Down
14 changes: 12 additions & 2 deletions library/math/real.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
#:inexact/
#:floor/
#:ceiling/
#:round/))
#:round/
#:fromfrac))

(in-package #:coalton-library/math/real)

Expand Down Expand Up @@ -264,7 +265,16 @@ Note: This does *not* divide double-float arguments."
(declare round/ (Integer -> Integer -> Integer))
(define (round/ a b)
"Divide two integers and round the quotient."
(round (exact/ a b))))
(round (exact/ a b)))

(declare fromfrac (Dividable Integer :a => Fraction -> :a))
(define (fromfrac q)
"Converts a fraction to a target type.
Specifically, target types must have an instance of `Dividable Integer :a`.
This conversion may result in loss of fidelity."
(general/ (numerator q) (denominator q))))

#+sb-package-locks
(sb-ext:lock-package "COALTON-LIBRARY/MATH/REAL")

0 comments on commit 7fc91f8

Please sign in to comment.