[erlang-questions] Emulating phantom types maybe

Michael Truog mjtruog@REDACTED
Fri Aug 26 00:19:09 CEST 2016


On 08/25/2016 02:47 PM, Tuncer Ayaz wrote:
> I've been wondering if I cannot tell Dialyzer that a function may only
> accept strings produced by a certain function, in a way emulating
> phantom types. While it's all a string, in such a function I expect a
> certain kind of string, say, lower-cased, to give a trivial example. I
> haven't figured out a way to encode that constraint. To be clear, the
> string value is just an example, and this isn't exclusively about
> strings.
>
> Basically, I want to subtype structurally-equivalent values.
>
> Why do I want this? I've run into a bug in the past, and this would
> have prevented it and also documented the code more clearly.
>
> >From what I understand, this isn't something that can be achieved with
> Dialyzer, or can it?
>
> So, here's a failed experiment trying to constrain need_lower/1 to
> accept only input of type lower/0.
>
> -type upper() :: string().
> -type lower() :: string().

-type ascii_lower() :: list(97..122).

The potential values gets much more complex for unicode, but Erlang/OTP doesn't have unicode to_lower (it requires external dependencies like https://github.com/rambocoder/unistring).

>
> -spec lowercase(upper()) -> lower().
> lowercase(U) -> string:to_lower(U).
>
> -spec need_lower(lower()) -> 'ok'.
> need_lower(_S) -> ok.
>
> %% Would be great if this wouldn't dialyze.
> wrong_type() ->  need_lower("UPPERCASE").
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>




More information about the erlang-questions mailing list