lt-core/lt-stdlib/ratio.lt

70 lines
1.7 KiB
Text
Raw Normal View History

export {
2024-12-24 12:51:36 +01:00
import "int.lt";
import "euclidean.lt";
/* Implementation of Rational Numbers
*/
2024-12-24 12:51:36 +01:00
let ratio-sign = λ{
p: machine.Int64 ~ machine.Word;
q: machine.Int64 ~ machine.Word;
}
↦ bool-xor (int-sign p) (int-sign q);
let ratio-scale = λ{
2024-12-24 12:51:36 +01:00
{
p: machine.Int64~machine.Word;
q: machine.Int64~machine.Word;
} : ~ <Ratio machine.Int64~machine.Word>;
n : machine.Int64 ~machine.Word;
} ↦ {
i* q n;
i* p n;
};
let ratio-normalize = λ{
2024-12-24 12:51:36 +01:00
p: machine.Int64 ~ machine.Word;
q: machine.Int64 ~ machine.Word;
} : ~ <Ratio machine.Int64 ~ machine.Word>
↦ {
let s = gcd p q;
i/ q s;
i/ p s;
};
let ratio-add = λ{
2024-12-24 12:51:36 +01:00
{
ap:machine.Int64~machine.Word;
aq:machine.Int64~machine.Word;
}: ~ <Ratio machine.Int64 ~ machine.Word> ;
{
bp:machine.Int64~machine.Word;
bq:machine.Int64~machine.Word;
}: ~ <Ratio machine.Int64 ~ machine.Word> ;
} ↦ {
let l = lcm aq bq;
let a = i/ l aq;
let b = i/ l bq;
i* aq a;
i+ (i* ap a) (i* bp b);
};
let ratio-mul = λ{
2024-12-24 12:51:36 +01:00
{
ap:machine.Int64~machine.Word;
aq:machine.Int64~machine.Word;
}: ~ <Ratio machine.Int64 ~ machine.Word> ;
{
bp:machine.Int64~machine.Word;
bq:machine.Int64~machine.Word;
}: ~ <Ratio machine.Int64 ~ machine.Word> ;
} ↦ ratio-normalize (i* ap bp) (i* aq bq);
2024-12-24 12:51:36 +01:00
/*
let fmt-ratio = λ{ p:; q:; }: ~<Ratio > ↦ {
fmt-int q;':';fmt-int p;
};
2024-12-24 12:51:36 +01:00
*/
}