Skip to content

Commit

Permalink
ddlog_std: Function to convert Option -> Result.
Browse files Browse the repository at this point in the history
Add three functions that make working with `Option<>` more ergonomic:

```
/* Transforms the `Option<'T>` into a `Result<'T, 'E>`,
 * mapping `Some{x}` to `Ok{v}` and `None` to `Err{e}`. */
function ok_or(o: Option<'T>, e: 'E): Result<'T, 'E>

/* Transforms `Option<'T>` into `Result<'T, 'E>`, mapping `Some{x}
 * to `Ok{v}` and `None` to `Err{e()}`.
 * Function `e` is only evaluated on error. */
function ok_or_else(o: Option<'T>, e: function(): 'E): Result<'T, 'E>

/* Returns `None` if the option is `None`, otherwise calls `f` with the
 * wrapped value and returns the result.
 */
function and_then(o: Option<'T>, f: function('T): Option<'U>): Option<'U>
```
  • Loading branch information
ryzhyk committed Oct 21, 2020
1 parent cae9df9 commit d7e1818
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions lib/ddlog_std.dl
Original file line number Diff line number Diff line change
Expand Up @@ -181,19 +181,48 @@ function unwrap_or_default(opt: Option<'A>): 'A {
option_unwrap_or_default(opt)
}

function to_set(o: Option<'X>): Set<'X> = {
function to_set(o: Option<'X>): Set<'X> {
match (o) {
Some{x} -> set_singleton(x),
None -> set_empty()
}
}
function to_vec(o: Option<'X>): Vec<'X> = {
function to_vec(o: Option<'X>): Vec<'X> {
match (o) {
Some{x} -> vec_singleton(x),
None -> vec_empty()
}
}

/* Transforms the `Option<'T>` into a `Result<'T, 'E>`,
* mapping `Some{x}` to `Ok{v}` and `None` to `Err{e}`. */
function ok_or(o: Option<'T>, e: 'E): Result<'T, 'E> {
match (o) {
Some{x} -> Ok{x},
None -> Err{e}
}
}

/* Transforms `Option<'T>` into `Result<'T, 'E>`, mapping `Some{x}
* to `Ok{v}` and `None` to `Err{e()}`.
* Function `e` is only evaluated on error. */
function ok_or_else(o: Option<'T>, e: function(): 'E): Result<'T, 'E> {
match (o) {
Some{x} -> Ok{x},
None -> Err{e()}
}
}

/* Returns `None` if the option is `None`, otherwise calls `f` with the
* wrapped value and returns the result.
*/
function and_then(o: Option<'T>, f: function('T): Option<'U>): Option<'U> {
match (o) {
None -> None,
Some{x} -> f(x)
}
}

/*
* Either
*/
Expand Down

0 comments on commit d7e1818

Please sign in to comment.