Search code examples
elixir

In Elixir, how to fix a nested list


In Elixir, I have the following list:

[ :juridical_person_document, [re_developments: [[properties: [[re_development: [:re_developer]]]]]], :legal_address ]

And my desired output would be this:

[ :juridical_person_document, re_developments: [properties: [re_development: [:re_developer]]], :legal_address ]

In other words, I want to remove the unnecessary square brackets. How can I achieve that?

I am aware that this can be achieved with recursion, but I didn't figure out how yet.


Solution

  • All of a sudden, Macro.postwalk/2 would work here.

    Macro.postwalk(input, fn [[x]] -> [x]; x -> x end)
    
    [
      :juridical_person_document,
      [re_developments: [properties: [re_development: [:re_developer]]]],
      :legal_address
    ]
    

    This hack uses the fact that lists, atoms, and tuples of size two are all valid AST.