地图模式匹配在Erlang,意外的错误(unbound) [英] map pattern matching in Erlang, unexpected error (unbound)

查看:401
本文介绍了地图模式匹配在Erlang,意外的错误(unbound)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码基本上是从J.A.的书中复制的:

  -module(mapz)。 
-export([count_chars / 1])。

count_chars(Str) - >
count_chars(Str,#{})。

count_chars([H | T],#{H:= N} = X) - > %行抛出
count_chars(T,X#{H:= N + 1});
count_chars([H | T],X))>
count_chars(T,X#{H => 1});
count_chars([],X) - > $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

$ b

  151> C(mapz)。 
mapz.erl:7:变量'H'是未绑定的
错误
152>

我明白H绑定的重要性,可以用于匹配地图中的一个键;并且,据我所知,它与第一个参数中的列表(string)的头部匹配,因此受到第二个参数(与映射匹配)的计算时间的约束。更重要的是,这个例子来自这本书,我怀疑它是正确的。这本书似乎在使用OTP17,但是现在我在20岁,想知道事情有变吗?但是哪些东西?



谢谢你的时间。

解决方案

在子句 count_chars([H | T],#{H:= N} = X) - > ... 编译器不认为 H 在第一个参数的模式匹配期间被绑定: [H | T] ,所以它无法匹配第二个参数#{H:= N} (我认为这可能是实际组装,请参阅我对这个主题的回答



但是,在地图库中需要使用的功能:

  count_chars(Str) - > 
count_chars(Str,#{})。

count_chars([H | T],X) - >
count_chars(T,maps:update_with(H,fun(V)→V + 1 end,1,X));
count_chars([],X) - >
X.

请参阅地图erlang doc



使用列表更短:foldl / 3

  count_chars(Str) - > 
列表:foldl(fun(C,Map) - > maps:update_with(C,fun(Count) - > Count + 1 end,1,Map)end,#{},Str)。


The code below is basically copied from J.A.'s book:

-module(mapz).
-export([count_chars/1]).

count_chars(Str) ->
    count_chars(Str, #{}).

count_chars([H|T], #{H := N}=X) -> % line that throws
    count_chars(T, X#{H := N+1});
count_chars([H|T], X) ->
    count_chars(T, X#{H => 1});
count_chars([], X) -> X.

however, compiling it in the shell gives me

151> c(mapz).
mapz.erl:7: variable 'H' is unbound
error
152>

I understand the importance of having H bound before it can be used for matching a key in a map; and, as far as I can tell, it is being matched to the head of the list(string) in the first argument, and is therefore bound by the time the second argument (matching against the map) is evaluated. More to the point, the example being from the book, I suspect it to be correct. The book seems to be using OTP17, however, and I'm now on 20, wonder if things have changed? But which things?

Thank you for your time.

解决方案

in the clause count_chars([H|T], #{H := N}=X) -> ... the compiler does not consider that H has been bound during the pattern matching of the first parameter : [H|T], so it is unable to pattern match the second parameter #{H := N} (I think it could be possible with the actual assembly, see my answer to this topic)

But there is the function you need in the maps library:

count_chars(Str) ->
    count_chars(Str, #{}).

count_chars([H|T],X) ->
    count_chars(T, maps:update_with(H,fun(V) -> V+1 end, 1,X));
count_chars([], X) ->
    X.

see documentation at Maps erlang doc

even shorter using the lists:foldl/3

count_chars(Str) -> 
    lists:foldl(fun(C,Map) ->  maps:update_with(C,fun(Count) -> Count+1 end, 1,Map) end, #{},Str).

这篇关于地图模式匹配在Erlang,意外的错误(unbound)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆