[erlang-questions] Temporarily violating record type constraints annoys dialyzer

Krzysztof Jurewicz krzysztof.jurewicz@REDACTED
Wed Nov 14 14:54:56 CET 2018


Roger Lipscombe writes:
>> I’ve implemented generation of from_map/2 and to_map/1; see this pull request: https://github.com/dieswaytoofast/dynarec/pull/7 . It should now be possible to convert records to maps and vice versa without writing boilerplate code.
>
> That's *almost* perfect ;-)
>
> Except that we load the code from JSON, using jiffy, which means that
> the keys are binary strings. I had a quick look at doing a PR for
> this, but I'm a bit sketchy when it comes to parse transforms, and I
> got side tracked.

A workaround (though likely not most efficient) may be to write the following function:

record_from_binary_proplist(RecordName, Props) ->
    BinaryFields = [list_to_binary(atom_to_list(Field)) || Field <- fields(RecordName)],
    from_map(
      RecordName,
      maps:from_list(
        [{list_to_atom(binary_to_list(Key)), Value}
         || {Key, Value} <- Props, lists:member(Key, BinaryFields)])).

Alternatively:

record_from_binary_proplist(RecordName, Props) ->
    FieldsByBinary = maps:from_list([{list_to_binary(atom_to_list(Field)), Field} || Field <- fields(RecordName)]),
    from_map(
      RecordName,
      lists:foldl(
        fun ({Key, Value}, MapAcc) ->
                case maps:find(Key, FieldsByBinary) of
                    {ok, KeyAtom} ->
                        maps:put(KeyAtom, Value, MapAcc);
                    error ->
                        MapAcc
                end
        end,
        #{},
        Props)).



More information about the erlang-questions mailing list