[erlang-questions] Emulating phantom types maybe

Tuncer Ayaz tuncer.ayaz@REDACTED
Fri Aug 26 04:03:32 CEST 2016


On 26/08/2016, Richard A. O'Keefe <ok@REDACTED> wrote:
> Can I suggest taking a more fundamental view?
>
> The basic presupposition here is that we want to have
> values that are the same as some standard value but
> tagged in some way, rather like the way Ada could do
>
> type Upper_String is new String;

Right.

> which would create a completely distinct Upper_String
> type that is structurally isomorphic to String and
> inherits all its operations, but can't be *mixed* with
> String.
>
> I want to ask the question "IS a string that's all
> upper case REALLY a string?"  In general, I don't
> think that's going to be true: the concatenation of
> two strings is a string, but the concatenation of
> two strings representing timestamps is not a string
> representing a timestamp; a substring of a string is
> a string, but a substring of a string representing a
> geographic location is a string representing a
> geographic location; the reversal of a string is a
> string, but the reversal of a string representing a
> British postcode is not a string representing a
> British postcode, and so on.

This is true, and I'm afraid my example was just bad,
even though string is a typical example for phantom types.

> I'm also thinking that Erlang is not a typeful language
> in the way that Haskell or even SML is, so that leaning
> hard on the type system might not be the best way to go.

True.

> In short, I'm suggesting that something like
> {upper,String} or {lower,String} or whatever with a
> run-time check required to get at the underlying string
> would not only be something the type checker can help
> with but might be a Good Idea anyway.

Yeah, same conclusion in the reply to Michael.

Another idea:
Although it has considerably more overhead than a string()
or a {'type',string()}, I thought it might be possible, and
sometimes practical, to pass around fun objects, where the
existing type specs should be able to express the constraint.

In that scenario, the result wouldn't be a tuple or a list of
characters, but a fun object that's meant to be evaluated to
a string in the consumer.

While this sounds like it would solve the issue, once you
adopt such a style, your code base might gain enough such
fun object generators that two of them will be similar
enough and you'll again run into the same bug.

> More generally, I note that C checkers like SPlint and
> Carillon let you devise your own annotations to extend
> the underlying type system.  Long term, something like
> that might be nice for the Dialyzer, but there'll be a
> lot of other things more urgent.

Anything in particular in Dialyzer that would be great
to have sooner than later?



More information about the erlang-questions mailing list