Question

I would like to map each square of an array (of n arrays) with Elixir.

With Ruby, this could be done with this bunch of code:

class Object
  def deep_map(&block)
    block.call(self)
  end
end

class Array
  def deep_map(&block)
    map {|e| e.deep_map(&block) }
  end
end

And then,

[
  [
    [nil, "foo"],
    [nil, nil]
  ],
  [
    [nil, "bar"],
    [nil, "baz"]
  ]
].deep_map {|el| el.to_s * 2 }

How could we do the same in Elixir? Thanks for your lights!

Was it helpful?

Solution

I played with it a bit and came up with this:

defmodule DeepMap do

def deep_map(list, fun) when is_list(list) do
    Enum.map(list, fn(x) -> deep_map(x, fun) end)
end

def deep_map(not_list, fun) do
    fun.(not_list)
end

end

There's probably a way to make it generic for all nested Enumerables, not just lists...


This is what it looks like when used:

iex(3)> c "/tmp/deep_map.ex"
[DeepMap]
iex(4)> deep_list = [
...(4)>   [
...(4)>     [nil, "foo"],
...(4)>     [nil, nil]
...(4)>   ],
...(4)>   [
...(4)>     [nil, "bar"],
...(4)>     [nil, "baz"]
...(4)>   ]
...(4)> ]
[[[nil, "foo"], [nil, nil]], [[nil, "bar"], [nil, "baz"]]]
iex(6)> DeepMap.deep_map deep_list, fn(x) -> {x,x} end     
[[[{nil, nil}, {"foo", "foo"}], [nil: nil, nil: nil]],
 [[{nil, nil}, {"bar", "bar"}], [{nil, nil}, {"baz", "baz"}]]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top