Skip to content

Commit

Permalink
Add Bool.then
Browse files Browse the repository at this point in the history
This method is useful if you want to create an Option based on the value
of a Boolean, i.e. something like this:

    if foo {
      Option.Some(thing)
    } else {
      Option.None
    }

Using Bool.then, we can reduce this to the following:

    foo.then fn { thing }

Changelog: added
  • Loading branch information
yorickpeterse committed Nov 4, 2023
1 parent a620408 commit 4fe8a03
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
11 changes: 11 additions & 0 deletions std/src/std/bool.inko
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ class builtin Bool {
fn pub false? -> Bool {
self == false
}

# Calls the supplied closure and wraps its return value in a `Some` if `self`
# is `true`, otherwise returns a `None`.
#
# # Examples
#
# true.then fn { 10 } # => Option.Some(10)
# false.then fn { 10 } # => Option.None
fn pub then[T](func: fn -> T) -> Option[T] {
if self { Option.Some(func.call) } else { Option.None }
}
}

impl ToInt for Bool {
Expand Down
5 changes: 5 additions & 0 deletions std/test/std/test_bool.inko
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,9 @@ fn pub tests(t: mut Tests) {
t.equal(fmt(true), 'true')
t.equal(fmt(false), 'false')
}

t.test('Bool.then') fn (t) {
t.equal(true.then fn { 10 }, Option.Some(10))
t.equal(false.then fn { 10 }, Option.None)
}
}

0 comments on commit 4fe8a03

Please sign in to comment.