2013-08-29 68 views
2

我想用Elixir來映射陣列(n個陣列)的每個正方形。Elixir陣列的深度圖

使用Ruby,這可能是與此一堆代碼來完成:

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 

然後,

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

我們怎麼可以做同樣的靈藥?感謝您的燈光!

回答

2

我打它一下,這個想出了:

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 

很可能有辦法使它通用於所有嵌套Enumerable S,不只是列出...


這是使用時的樣子:

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"}]]] 
+1

太棒了,謝謝@legoscia!完美地工作! – Doug