type switch

Jarrett Billingsley jarrett.billingsley at gmail.com
Tue Sep 1 17:06:21 PDT 2009


On Tue, Sep 1, 2009 at 7:39 PM, Paul D.
Anderson<paul.d.removethis.anderson at comcast.andthis.net> wrote:
> I came across Lava, an experimental programming language ("What's hotter than Java?") http://lavape.sourceforge.net/LavaHomePage.htm Lava has some curious features (they claim to have no syntax, but the syntax is just hidden by the "programming environment").
>
> One of the evils of other programming languages, according to the website, is the infamous type cast: "Type casts are not only ugly, nasty, and annoying but much worse: their justification can only be assessed on the basis of a more comprehensive understanding of the dynamic program behavior in general."
>
> While I don't feel quite that strongly about type casts, one use case for casting does bother me: Using a generic object as the type of a member, and then specializing the object when you use it.
>
> A good example is a Token type in a lexer. The token typically has a line and column number, a string (the text of the token), a token type (an enumeration or int) and a value. The value is an integer for an integer token, a string for a string, an enum for a symbol or keyword, etc. So the type of the value field is "object", and you use the token type to tell you how to cast the value field when you use it.
>
> The Lava solution to this problem is to allow an explicit type switch:
>
> switch (value.type) {
>
> case int:  // value is an int
>    value += 3;
>    break;
>
> case string: // value is a string
>    string sub = substring(value, 1, 5);
>    break;
>
> case symbol: // value is a symbol type
>    int index = value.getSymbolIndex;
>    break;
>
> }
>
> (Lava doesn't actually give an example of a type switch -- I just guessed at what it would look like.)
>
> Anyone else think this is a good idea?
>
> Does anyone know of another language that does this? (I don't have much knowledge of functional or logical languages.)

Just looks like simple pattern matching. It's very common in
functional languages.



More information about the Digitalmars-d mailing list