【问题标题】:Store a list in Erlang ETS在 Erlang ETS 中存储一个列表
【发布时间】:2015-02-17 23:54:16
【问题描述】:

我试图在 ETS 中插入一个列表以便稍后退出,由于某种原因,它说这是一个错误的参数。我不确定我是否插入不正确。

难道就不能在 ETS 中插入列表吗?

违规行是ets:insert(table, [{parsed_file, UUIDs}])。

代码如下:

readUUID(Id, Props) ->
    fun () -> 
        %%TableBool = proplists:get_value(table_bool, Props, <<"">>),
        [{_, Parsed}] = ets:lookup(table, parsed_bool),
        case Parsed of
          true  ->
            {uuids, UUIDs} = ets:lookup(table, parsed_bool),
            Index = random:uniform(length(UUIDs)),
            list_to_binary(lists:nth(Index, UUIDs));
          false -> 
            [{_, Dir}] = ets:lookup(table, config_dir),
            File = proplists:get_value(uuid_file, Props, <<"">>),
            UUIDs = parse_file(filename:join([Dir, "config", File])),
            ets:insert(table, [{parsed_file, {uuids, UUIDs}}]),
            ets:insert(table, [{parsed_bool, true}]),
            Index = random:uniform(length(UUIDs)),
            list_to_binary(lists:nth(Index, UUIDs))
        end
    end.

parse_file(File) ->
  {ok, Data} = file:read_file(File),
  parse(Data, []).

parse([], Done) ->
  lists:reverse(Done);

parse(Data, Done) ->
  {Line, Rest} = case re:split(Data, "\n", [{return, list}, {parts, 2}]) of
                   [L,R] -> {L,R};
                   [L]   -> {L,[]}
                 end,
  parse(Rest, [Line|Done]).

【问题讨论】:

  • 它对我有用...您确定调用 insert 的进程是 ets 或表的所有者是公共的吗?我没有看到负责创建它的代码。 Check this.
  • 您应该知道实际上只能将元组放入 ETS 表中,而不是列表。因此,当您执行 ets:insert(table, [...]) 时,您实际上是在列表中插入元组,而不是它自己的列表。当您执行ets:lookup(table, Key) 时,您将返回具有该键的元组列表。

标签: list erlang ets


【解决方案1】:

如果您在同一个过程中使用类似的东西创建表

ets:new(table, [set, named_table, public]).

那你应该没问题。默认权限受到保护,只有创建进程可以写入。

【讨论】:

    【解决方案2】:

    作为我对仅包含元组的 ets 表以及 ets:lookup/2 在代码中返回以下行的评论的后续:

            {uuids, UUIDs} = ets:lookup(table, parsed_bool),
    

    总是会产生错误,因为ets:lookup/2 返回一个列表。上面的调用 3 行可能会成功。似乎您正在尝试使用键 parsed_bool 在 table 中进行 2 次查找,并期望得到 2 种不同类型的答案:{_, Parsed} 和 {uuids, UUIDs}。请记住,ETS 不提供键值表,而是提供元组表,其中一个元素(默认第一个元素)是键,并且执行 ets:lookup/2 会返回具有该键的元组列表。能取回多少取决于表的属性。

    查看ETS tables的文档。

    【讨论】:

      猜你喜欢
      • 2014-11-30
      • 2015-09-20
      • 2021-01-19
      • 2016-09-10
      • 2016-06-03
      • 2012-10-14
      • 2018-09-25
      • 2011-02-17
      • 2012-08-07
      相关资源
      最近更新 更多