Help writing a map_join function

It appears I am having a random brain freeze, but… how do I write a function that’d turn a nested list into a string, like this:

magic_function([["a", "b", "c"], ["d", "e", "f"]]) # => "($1, $2, $3), ($4, $5, $6)"

:thinking:

Is it something like this?

a |> Enum.map(fn chars -> s=Enum.join(chars, ", "); "(#{s})" end) |> Enum.join(", ")

result in "(a, b, c), (d, e, f)"

@csadewa hmm, not really. The output must contain numbers, like in example from my original post.

Then just reduce with counter.

1 Like

Ok, I finally arrived at something:

fold_list_item = fn item, {so_far, output} ->
  length = length(item)

  result =
    (for i <- 1..length, do: "$#{so_far + i}")
    |> Enum.join(", ")

  {so_far + length, ["(#{result})" | output]}
end

[["a", "b"], ["c", "d", "e"], ["f"]]
|> Enum.reduce({0, []}, fold_list_item)
|> elem(1)
|> Enum.reverse()
|> Enum.join(", ")
|> IO.inspect()
# => "($1, $2), ($3, $4, $5), ($6)"

hmmm, you could map character to numbers by creating function like this

def char_to_num_id(list_of_chars) do
  a
  |> Enum.flat_map(fn x -> x end) 
  |> Enum.uniq() 
  |> Enum.with_index() 
  |> Enum.map(fn {char, index} -> {char, "$#{index+1}"} end) 
  |> Enum.into(%{})  
end
%{"a" => "$1", "b" => "$2", "c" => "$3", "d" => "$4", "e" => "$5", "f" => "$6"}

combine with function above:

def magic_function(list_of_chars) do
  char_to_id = char_to_num_id(list_of_chars)
  
  list_of_chars 
  |> Enum.map(fn chars ->
    ids = Enum.map(chars, fn char -> char_to_id[char] end)     
    s = Enum.join(ids, ", ")
    "(#{s})" 
  end) 
  |> Enum.join(", ")
end
1 Like