From 334f11c5167402d43d0d7e52110e61ecba20ded0 Mon Sep 17 00:00:00 2001 From: Peter Saxton Date: Wed, 2 Dec 2020 16:42:37 +0000 Subject: implement a lazy or function --- src/gleam/result.gleam | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src') diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index 2ebf2ef..76ee0e1 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -202,6 +202,29 @@ pub fn or(first: Result(a, e), second: Result(a, e)) -> Result(a, e) { } } +/// Return the first value if it is Ok, otherwise evaluates the given function for a fallback value. +/// +/// ## Examples +/// +/// > or(Ok(1), Ok(2)) +/// Ok(1) +/// +/// > or(Ok(1), Error("Error 2")) +/// Ok(1) +/// +/// > or(Error("Error 1"), Ok(2)) +/// Ok(2) +/// +/// > or(Error("Error 1"), Error("Error 2")) +/// Error("Error 2") +/// +pub fn lazy_or(first: Result(a, e), second: fn() -> Result(a, e)) -> Result(a, e) { + case first { + Ok(_) -> first + Error(_) -> second() + } +} + /// Combine a list of results into a single result. /// If all elements in the list are Ok then returns an Ok holding the list of values. /// If any element is Error then returns the first error. -- cgit v1.2.3