Hello, guys!
type
Maybe = tuple or object
Some[T] = tuple
value: T
None = tuple
proc either[T](m: Maybe, alternative: T): T =
if (type(m) == type(Some)):
return m.value
else:
return alternative
proc main(): void =
var m: Some[int] = (value: 10)
var t: int
t = either(m, 11)
echo $t
What wrong with this code? If I compile this, the error is
maybe.nim(19, 13) Error: type mismatch: got (Some[system.int], int literal(11))
but expected one of:
proc either[T](m: Maybe; alternative: T): T
changing last two lines to
t = either[int](m,11)
echo $t
leads to
maybe.nim(19, 13) Error: cannot instantiate: either[int]; got 1 type(s) but expected 2
If I remove main proc at all then it compiles without error, so I expect declaration of either proc is correctTwo things. First of all, Maybe is a concept and thus resolved at compile time. The correct way to check whether your argument is of type Some[T] or not is by:
proc either[T](m: Maybe, alternative: T): T =
when m is Some[T]:
return m.value
else:
return alternative
And second, it looks like some sort of bug with concepts. If you replace m: Maybe by m: tuple or object it works now https://glot.io/snippets/epais84qfv.
But if you want to make it work at runtime you should have a look at how options work https://nim-lang.org/docs/options.html.
Sounds that you actually need
type
Some[T] = tuple
value: T
None = tuple
Maybe[T] = Some[T] or None
proc either[T](m: Maybe[T], alternative: T): T =
when m is Some[T]:
return m.value
else:
return alternative