Erlang地图中的非法格局 [英] illegal pattern in map of Erlang

查看:92
本文介绍了Erlang地图中的非法格局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

-module(map_demo).
-export([count_characters/1]).

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

count_characters([H|T], #{ H => N } = X) ->
    count_characters(T, X#{ H := N+1 });
count_characters([H|T], X) ->
    count_characters(T, X#{ H => 1});
count_characters([], X) ->
    X.

当编译Erlang shell中的代码时,它报告了以下错误:

when compiling the code in the Erlang shell, it reported the following errors:

1> c(map_demo).
map_demo.erl:7: illegal pattern
map_demo.erl:8: variable 'N' is unbound
map_demo.erl:10: illegal use of variable 'H' in map
map_demo.erl:7: Warning: variable 'H' is unused
error

I 在Erlang新的,只是找不到任何错误我自己。如何纠正?

I'm new in Erlang, and just can't find anything wrong by myself. How to correct it?

推荐答案

IRC的答案(#erlang @ freenode):

The answers from IRC (#erlang@freenode):


  1. 变量作为匹配中的键不受支持(版本17.0)

  2. 更一般的问题影响函数的匹配参数:第7行 H 匹配2次;或者一次,然后用于匹配N。 (此问题也出现在二进制文件中)

  1. variables as keys in matches are not supported yet (release 17.0)
  2. A more general issue affects matching arguments of a function: line 7's H is matched 2 times; or once and used to match N then. (This issue also appears with binaries)

这个应该在下一个版本中解决。

This should be solved in the coming releases.

从版本17 起的作品:

As of release 17 this works:

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

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

%% maps module functions cannot be used as guards (release 17)
%% or you'll get "illegal guard expression" error
count_characters([H|T], X) ->
    case maps:is_key(H,X) of
        false -> count_characters(T, maps:put(H,1,X));
        true  -> Count = maps:get(H,X),
                         count_characters(T, maps:update(H,Count+1,X))
    end;
count_characters([], X) ->
        X.

这是另一个版本(仅在18年测试),稍微更相似在书中的一个:

Here is another version (only tested on 18) that is slightly more similar to the one in the book:

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

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

count_characters([H|T], X) ->
    case maps:is_key(H,X) of
        false -> count_characters(T, X#{ H => 1 });
        true  -> #{ H := Count } = X,
                 count_characters(T, X#{ H := Count+1 })
    end;
count_characters([], X) ->
        X.

这篇关于Erlang地图中的非法格局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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