On Monday, 9 April 2018 at 07:07:58 UTC, Chris Katko wrote:
On Monday, 9 April 2018 at 07:02:50 UTC, Hasen Judy wrote:
IMO, this is one more reason why sum-types should be built
into the language compiler, instead of being implemented in
user-space.
+1. Any time you have to "create" a fundamental feature in a
language... from inside the language itself... you're going to
have confusing error messages, and a huge uphill battle.
I agree in general, but in this case it's actually completely
doable. In fact, I've done it myself: check out 'sumtype' on
code.dlang.org. You can replace 'Algebraic' with 'SumType' and
'visit' with 'match' in helxi's example, and everything Just
Works™:
import sumtype;
import core.stdc.stdio;
SumType!(T, string) fib_nth(T)(T n)
{
return n % 15
? n % 5
? n % 3
? SumType!(T, string)(n)
: SumType!(T, string)("Fizz")
: SumType!(T, string)("Buzz")
: SumType!(T, string)("Fizzbuzz");
}
void main() @nogc
{
foreach (i; 1 .. 101)
{
fib_nth(i).match!(
(string s) => printf("%s\n", s.ptr),
(int n) => printf("%i\n", n)
);
}
}