louise
The Louise language: compiler, runtime, std, tooling
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#125 · main · 16 min 13 s
0Étoiles
0Forks
40Issues
| 1 | // Dec (ADR 0070): a 128-bit fixed-point decimal for money. |
| 2 | |
| 3 | import std/dec.{type Dec} |
| 4 | import std/dict |
| 5 | import std/io |
| 6 | import std/process.{type proc} |
| 7 | import std/result |
| 8 | |
| 9 | fn d :: s: String -> Dec |
| 10 | { |
| 11 | result.expect (dec.parse s) "a decimal" |
| 12 | } |
| 13 | |
| 14 | pub fn main :: -> () / <io, proc> |
| 15 | { |
| 16 | // Exact decimal arithmetic: 0.1 + 0.2 == 0.3, unlike Float. The fixed |
| 17 | // scale is canonical: 1.20 and 1.2 are one value. |
| 18 | io.println |
| 19 | "{d "0.1" + d "0.2" == d "0.3"} {d "1.20" == d "1.2"} {d "0.1" * d "0.1"}" |
| 20 | // Division rounds half-even at the 18th place; rem is exact. |
| 21 | io.println |
| 22 | "{d "1" / d "3"} {d "2" / d "3"} {d "7" % d "2"} {d "7.5" % d "2"} {-d "1.5"}" |
| 23 | // round ~places:, the money operation (half-even). |
| 24 | io.println |
| 25 | "{dec.round (d "2.5") ~places: 0} {dec.round (d "1.005") ~places: 2} {dec.round (d "1.015") ~places: 2} {dec.round (d "-2.5") ~places: 0}" |
| 26 | // show trims trailing zeros; to_int truncates; abs. |
| 27 | io.println |
| 28 | "{d "1.20"} {d "42"} {dec.to_int (d "-12.99")} {dec.abs (d "-2.5")}" |
| 29 | // Float conversions are explicit and go through the shortest decimal. |
| 30 | io.println |
| 31 | "{dec.from_float 0.1} {dec.to_float (d "0.1")} {dec.from_float (0.0 / 0.0)}" |
| 32 | // The raw count of 10^-18 units, for binary codecs. |
| 33 | io.println "{dec.scaled (d "1.5")} {dec.from_scaled 1500000000000000000}" |
| 34 | // The range's edges: the minimum is a Dec; one quantum past the |
| 35 | // maximum is not (the magnitude is unsigned, so -2^127/10^18 parses). |
| 36 | io.println "{dec.parse "-170141183460469231731.687303715884105728"}" |
| 37 | io.println "{dec.parse "170141183460469231731.687303715884105728"}" |
| 38 | // A Dec is a key like any other (the hash is pinned, both backends). |
| 39 | let prices = dict.from_list [(d "1.20", "one"), (d "2.5", "two")] |
| 40 | io.println "{dict.get prices (d "1.2")} {dict.get prices (d "12")}" |
| 41 | // And a value like any other: it can be sent. |
| 42 | let inbox = process.subject () |
| 43 | let _ = process.spawn fn { process.send inbox (d "3.14" * d "2") } |
| 44 | io.println "{process.receive_forever inbox}" |
| 45 | } |
| 46 | //> True True 0.01 |
| 47 | //> 0.333333333333333333 0.666666666666666667 1 1.5 -1.5 |
| 48 | //> 2 1 1.02 -2 |
| 49 | //> 1.2 42 -12 2.5 |
| 50 | //> Ok(0.1) 0.1 Error(not a finite decimal in range: NaN) |
| 51 | //> 1500000000000000000 Ok(1.5) |
| 52 | //> Ok(-170141183460469231731.687303715884105728) |
| 53 | //> Error(not a decimal: "170141183460469231731.687303715884105728") |
| 54 | //> Some(one) None |
| 55 | //> 6.28 |