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#91 · main · 15 min 44 s
0Étoiles
0Forks
40Issues
| 1 | /// Optional values (`Option` is in the prelude). |
| 2 | /// |
| 3 | /// `Option<a>` is for a value that may be absent, where absence is not a |
| 4 | /// failure (a key not in a dictionary, a variable not set). A failure with |
| 5 | /// a reason is a `Result` (ADR 0024); `to_result` turns one into the other. |
| 6 | |
| 7 | /// Whether `o` is `Some`. |
| 8 | pub fn is_some :: o: Option<a> -> Bool |
| 9 | { |
| 10 | match o { Some(_) -> True, None -> False } |
| 11 | } |
| 12 | |
| 13 | /// Whether `o` is `None`. |
| 14 | pub fn is_none :: o: Option<a> -> Bool |
| 15 | { |
| 16 | match o { Some(_) -> False, None -> True } |
| 17 | } |
| 18 | |
| 19 | /// Apply `f` to the value of a `Some`. |
| 20 | pub fn map :: o: Option<a> f: fn(a) -> b / <e> -> Option<b> / <e> |
| 21 | { |
| 22 | match o { Some(x) -> Some(f x), None -> None } |
| 23 | } |
| 24 | |
| 25 | /// Continue with `next` on `Some`; for `use`: |
| 26 | /// `use user <- option.then(find_user(name))`. |
| 27 | pub fn then :: o: Option<a> next: fn(a) -> Option<b> / <e> -> Option<b> / <e> |
| 28 | { |
| 29 | match o { Some(x) -> next x, None -> None } |
| 30 | } |
| 31 | |
| 32 | /// The value of a `Some`, or `default`. |
| 33 | pub fn unwrap_or :: o: Option<a> default: a -> a |
| 34 | { |
| 35 | match o { Some(x) -> x, None -> default } |
| 36 | } |
| 37 | |
| 38 | /// `Ok` with the value of a `Some`, or `Error(reason)`: absence becomes |
| 39 | /// a failure with a reason. |
| 40 | pub fn to_result :: o: Option<a> reason: x -> Result<a, x> |
| 41 | { |
| 42 | match o { Some(x) -> Ok(x), None -> Error(reason) } |
| 43 | } |
| 44 | |
| 45 | /// The values of the `Some`s, in order. |
| 46 | pub fn values :: options: List<Option<a>> -> List<a> |
| 47 | { |
| 48 | match options |
| 49 | { [] -> [] |
| 50 | , [Some(x), ..rest] -> [x, ..values rest] |
| 51 | , [None, ..rest] -> values rest |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /// `o` if it is `Some`, else `other` (Haskell's `<|>` for `Maybe`). |
| 56 | pub fn or :: o: Option<a> other: Option<a> -> Option<a> |
| 57 | { |
| 58 | match o { Some(x) -> Some(x), None -> other } |
| 59 | } |
| 60 | |
| 61 | /// `o` if it is `Some`, else the result of `other` (called only then). |
| 62 | pub fn lazy_or :: o: Option<a> other: fn() -> Option<a> / <e> -> Option<a> / <e> |
| 63 | { |
| 64 | match o { Some(x) -> Some(x), None -> other () } |
| 65 | } |
| 66 | |
| 67 | /// `f` applied to both values if both are `Some`, else `None`. |
| 68 | pub fn map2 :: |
| 69 | a: Option<a> |
| 70 | b: Option<b> |
| 71 | f: fn(a, b) -> c / <e> |
| 72 | -> Option<c> / <e> |
| 73 | { |
| 74 | match (a, b) { (Some(x), Some(y)) -> Some(f x y), _ -> None } |
| 75 | } |