When attempting to pattern match an Option[T] I receive runtime errors if it is none
import gara
import random
randomize()
proc test(): Option[int] =
let r: int = rand(10)
if r > 5: some(1)
else: none(int)
let foo: Option[int] = test()
match(foo):
Some(1): echo "foo is 1"
Some(@val): echo "foo is " & $val
_: echo "none"
I'm not sure if this is intentional?
The desired functionality is of course to safely unpack the value for pattern matching if it is some() and skip that match branch if it doesn't qualify as some() (ie. none()) but because gara.Some() explicitly calls get(Option[T]) which errors when the value is none() the match errors at runtime if foo is none()
Any insight would be much appreciated. Coming from a lot of Rust reading since I've been away from Nim and really liking the way Rust's Result<T, E> and Option<T> play with pattern matching, it's definitely my preferred way to conditionally unpack an optional value. if opt.isSome: opt.get and having to explicitly store the unpacked value to work with it just feels too messy and I like what Gara could offer to this scenario.
I understand that gara.Some() is simply an unpacker function, which I imagine are not meant to be so versatile. Perhaps consideration for Option[T] needs to just be native to the library?
Edit: I realize that this could be avoided by checking foo.isSome before matching, but that defeats the purpose of matching Option types in the first place, in my opinion.
When attempting to pattern match an
Option[T]
I receive runtime errors if it isnone
I'm not sure if this is intentional?
The desired functionality is of course to safely unpack the value for pattern matching if it is
some()
and skip that match branch if it doesn't qualify assome()
(ie.none()
) but becausegara.Some()
explicitly callsget(Option[T])
which errors when the value isnone()
the match errors at runtime iffoo
isnone()
Any insight would be much appreciated. Coming from a lot of Rust reading since I've been away from Nim and really liking the way Rust's
Result<T, E>
andOption<T>
play with pattern matching, it's definitely my preferred way to conditionally unpack an optional value.if opt.isSome: opt.get
and having to explicitly store the unpacked value to work with it just feels too messy and I like what Gara could offer to this scenario.I understand that
gara.Some()
is simply an unpacker function, which I imagine are not meant to be so versatile. Perhaps consideration forOption[T]
needs to just be native to the library?Edit: I realize that this could be avoided by checking
foo.isSome
before matching, but that defeats the purpose of matching Option types in the first place, in my opinion.