alehander92 / gara

MIT License
103 stars 4 forks source link

Matching Option[T] #24

Closed zajrik closed 3 years ago

zajrik commented 5 years ago

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.

zajrik commented 3 years ago

Closing this now that fusion/matching is available.

https://nim-lang.org/blog/2021/03/10/fusion-and-pattern-matching.html