gpt4 book ai didi

erlang - 空 map 模式甚至可以匹配非空 map

转载 作者:行者123 更新时间:2023-12-04 11:23:27 27 4
gpt4 key购买 nike

我正在尝试解决状态的问题

Write a function map_search_pred(Map, Pred) that returns the first element {Key,Value} in the map for which Pred(Key, Value) is true.



我的尝试看起来像
map_search_pred(#{}, _)     -> {};
map_search_pred(Map, Pred) ->
[H|_] = [{Key, Value} || {Key, Value} <- maps:to_list(Map), Pred(Key, Value) =:= true],
H.

运行此命令时,我看到的输出为
1> lib_misc:map_search_pred(#{1 => 1, 2 => 3}, fun(X, Y) -> X =:= Y end).
{}
2> lib_misc:map_search_pred(#{1 => 1, 2 => 3}, fun(X, Y) -> X =:= Y end).
{}
3> maps:size(#{}).
0
4>

我怎么确定?
我拉出第一个子句,所以它看起来像
map_search_pred(Map, Pred)  ->
[H|_] = [{Key, Value} || {Key, Value} <- maps:to_list(Map), Pred(Key, Value) =:= true],
H.

并再次运行
1> lib_misc:map_search_pred(#{1 => 1, 2 => 3}, fun(X, Y) -> X =:= Y end).
{1,1}
2> lib_misc:map_search_pred(#{}, fun(X, Y) -> X =:= Y end).
** exception error: no match of right hand side value []
in function lib_misc:map_search_pred/2 (/Users/harith/code/IdeaProjects/others/erlang/programmingErlang/src/lib_misc.erl, line 42)
3>

最佳答案

根据map documentation:

Matching an expression against an empty map literal will match its type but no variables will be bound:

#{} = Expr

This expression will match if the expression Expr is of type map, otherwise it will fail with an exception badmatch.



但是可以使用 erlang:map_size代替:
map_search_pred(Map, _) when map_size(Map) == 0 ->
{};
map_search_pred(Map, Pred) ->
[H|_] = [{Key, Value} || {Key, Value} <- maps:to_list(Map), Pred(Key, Value) =:= true],
H.

关于erlang - 空 map 模式甚至可以匹配非空 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829730/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com