[erlang-questions] Asserting exact maps
Alexander Mihajlovic
a@REDACTED
Wed Oct 11 11:05:16 CEST 2017
The function maps:with/2 [1] will get you most of the way there. It lets
you filter a map to only contain keys in your given list. After that
it's only a matter of matching the filtered map against the original, or
you could check their lengths like Attila Rajmund Nohl wrote.
1> X = #{one => "1", two => "2"}.
#{one => "1",two => "2"}
2> X = maps:with([one, two], X).
#{one => "1",two => "2"}
3> Y = #{one => "1", two => "2", three => "3"}.
#{one => "1",three => "3",two => "2"}
4> Y = maps:with([one, two], Y).
** exception error: no match of right hand side value #{one => "1",two
=> "2"}
[1]: http://erlang.org/doc/man/maps.html#with-2
On Wed, Oct 11, 2017, at 10:50, Attila Rajmund Nohl wrote:
> 2017-10-11 10:47 GMT+02:00 Technion <technion@REDACTED>:
> > Hi,
> >
> >
> > I'm wondering if there is a simple process I can use to verify a map only
> > contains valid variables. Consider the following example:
> >
> >
> > 2> Checkmaps = fun(M) ->
> > 2> #{"one" := One, "two" := _Two} = M,
> > 2> One end.
> > #Fun<erl_eval.6.99386804>
> >
> > % These crash as expected
> >
> > 5> Checkmaps(#{"test" => one }).
> > ** exception error: no match of right hand side value #{"test" => one}
> > 6> Checkmaps(#{"one" => one }).
> > ** exception error: no match of right hand side value #{"one" => one}
> >
> >
> > % This works as expected
> >
> > 7> Checkmaps(#{"one" => one, "two" => two }).
> > one
> >
> > % This however also runs - I would like it to crash like the first example
> >
> > 8> Checkmaps(#{"one" => one, "two" => two, "three" => test }).
> >
> > one
> >
> > The use case here is I'm pulling external data - anything I'm not expecting
> > is not a happy path. Any assistance appreciated.
>
> Check also the size of the map. If it's greater than expected, it has
> extra elements.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
More information about the erlang-questions
mailing list