module util::Maybe
rascal-0.40.16
Encapsulate any optional value using Maybe[&T]
.
Usage
import util::Maybe;
data Maybe
Generic data type to encapsulate any value, optionally.
data Maybe[&A]
= nothing()
| just(&A val)
;
Examples
rascal>import util::Maybe;
ok
nothing() can always be assigned to a variable of type Maybe[Anytype]
rascal>Maybe[int] myIntOption = nothing();
Maybe[int]: nothing()
another example of the same feature:
rascal>Maybe[str] myStrOption = nothing();
Maybe[str]: nothing()
if you do have a value, the type of the parameter of just
must align:
rascal>myStrOption = just("a string");
Maybe[str]: just("a string")
If you don't align the type of the parameter with the parameter type of Maybe
, static errors ensue:
rascal>myStrOption = just(42);
|prompt:///|(19,2,<1,19>,<1,21>): Expected Maybe[str], but got Maybe[int]
Advice: |https://www.rascal-mpl.org/docs/Rascal/Errors/CompileTimeErrors/UnexpectedType|
ok
Here's a function that sometimes returns a value and otherwise returns nothing()
:
Maybe[int] indexOf(list[int] haystack, int needle) {
for (i <- index(haystack), haystack[i] == needle) {
return just(i);
}
return nothing();
}