Creaating a new Key Value dict from previous dict

32 Views Asked by At

So, I have a dict called conquered. The porpouse of this dict is store a Key, Value dict of lists to use concurrency on a divide and conquer method to search for values.

The code goes on:

-module(divide).
-export([divide_the_cache/4]).

-define(divided, dict:new()).

divide_the_cache(cache, divided, thread_index, acc) ->
    case length(cache) =< acc of
        thread_index ->
            l = lists:merge([lists:nth(thread_index, divided)], [lists:nth(acc, cached)]);
            conquered = dict:append(thread_index, l, dict:from_list(divided));
            thread_index = if length(l) == 24 -> thread_index = thread_index + 1, end;

            divide_the_cache(cache, conquered, thread_index, acc+1);
    end.

I'm getting:

divide.erl:10:69: syntax error before: ';'
%   10|             conquered = dict:append(thread_index, l, dict:from_list(divided));
%     | 

When I'm not using function composition on dict:append I get:

divide.erl:10:36: syntax error before: ';'
%   10|             d_list = dict:from_list(divided);
%     |                                             ^

I've already consulted the documentation and sites across the web, but could encounter an example(except to work with dict:from_list) and follow the docs trying on the repl.

What could going wrong? What is the best way to achieve what I need?

Thanks in advance, Lukas.

1

There are 1 best solutions below

0
Brujo Benavides On

Your code have multiple issues, most of them syntactic ones. Let me try to rewrite it in a more syntactically correct way. Then, you'll need to fix whatever semantics you want to give to it on your own:

-module(divide).
-export([divide_the_cache/4]).

divide_the_cache(Cache, Divided, ThreadIndex, Acc)
  when length(Cache) =< Acc ->
    L = lists:merge(
          [lists:nth(ThreadIndex, dict:to_list(Divided))],
          [lists:nth(Acc, Cache)]
        ),
    Conquered = dict:append(ThreadIndex, L, Divided),
    NewThreadIndex =
      case length(L) of
        24 -> ThreadIndex + 1;
        _ -> ThreadIndex
      end,
    divide_the_cache(Cache, Conquered, NewThreadIndex, Acc+1).

What I changed:

  1. -define in Erlang is for macros and you were not using the ?divided macro anywhere.
  2. Variables in Erlang start in uppercase.
  3. case length(Cache) =< Acc of ThreadIndex -> made no sense to me, so I replaced it with a guard (when length(Cache) =< Acc).
  4. Divided should be either a dict or a list but it's treated as a list first and a dict later… so I decided that it's always a dict and thus, for lists:nth/2, I used dict:to_list/1.
  5. In Erlang, expressions end in , (not ;) and functions end in ..
  6. You shouldn't write else-less if's in Erlang, so I turned your if into a case statement.
  7. Variables in Erlang can't be re-bound, that's why I introduced NewThreadIndex.