Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 26, 2021 04:04 am GMT

Rate my Union-Type idea Janky.

So, I want my language to have union types, because they are really convenient for storing data of different types in one variable. - I'd go as far to say that it's the most elegant solution a strongly-typed language could have for such a problem.

So, how do they work?
Well, I've based my idea on TypeScript's union-types... for the most part.

As a refresher, here is how you create and use union types.

type QResponse = number|string;function answer_question(ans:QResponse):void {    if(typeof ans === "string")        console.log(`Responded with string: "${ans}"`);    else console.log(`Responded with number: "${ans}"`);}

But, Janky will be a statically typed language, and won't have room for such a silly concept such as typeof.
Well, to get around this, to do anything useful with a value of type TX|TY, you must pass it to a function that has overloads for all types.

For example, if you have byte|BitSet<1>, and you want to pass it to a function f, there must be at least two overloads for f, f(byte) <return-type> and f(BitSet<8>) <return-type>.

Here's an expanded version:

type DiscrimType = unsigned int|string;User find_user(unsigned int user_id) {    // Code...}User find_user(string       user_tag) {    // Code...}User get_user(string user_tag) { /* Code... */ }User fetch_user(DiscrimType dsc) { /* Code... */ }User retrieve_user(DiscrimType dsc) { /* Code... */ }User retrieve_user(string s) { /* ... */ }User retrieve_user(unsigned long ul) { /* ... */ }// If Janky ever has a compiler, this would// not compile.// If Janky is interpreted, at runtime,// an error (`AmbiguityError`) is thrown.DiscrimType discriminator = getDescriminator();find_user(discriminator);// Works.get_user(discriminator);// Does not work.// It is not "promised" that `discriminator` is// a `string`.fetch_user(discriminator);// Has to pass `discriminator`'s// value to another function.retrieve_user(145959);// AmbiguityError: unsigned long or// DiscrimType:[unsigned long]|number?

Any and all feedback, positive, negative, neutral, and questions are appreciated.

Thanks!
Cheers!


Original Link: https://dev.to/baenencalin/rate-my-union-type-idea-janky-40oa

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To