2017-01-05 78 views
3

列出要做的:转换嵌套的元组灵药

def nested_tuple_to_list(tuple) when is_tuple(tuple) do 
    ... 
end 

期望得到:

iex> example = {"foo", "bar", {"foo", "bar"}} 
    iex> example_as_list = nested_tuple_to_list(example) 
    iex> example_as_list 
    ["foo", "bar", ["foo", "bar"]] 

我的问题是:如何做到这一点的最好方法是什么?

回答

1

有一个库可以做到这一点以及嵌套数据的其他转换。

iex(1)> h PhStTransform.transform 

     def transform(data_structure, function_map, depth \\ []) 

使用给定function_map转化任何药剂data structure

function_map应该包含对应于数据类型的密钥被变换为 。每个键必须映射到将该数据类型和深度列表作为参数的函数。

depth应始终保持默认值,因为它是用于内部递归。

实例

iex> atom_to_string_potion = %{ Atom => fn(atom) -> Atom.to_string(atom) end } 
iex> PhStTransform.transform([[:a], :b, {:c, :e}], atom_to_string_potion) 
[["a"], "b", {"c", "e"}] 

iex> foo = {"foo", "bar", {"foo", "bar"}} 
{"foo", "bar", {"foo", "bar"}} 

iex> PhStTransform.transform(foo, %{Tuple => fn(tuple) -> Tuple.to_list(tuple) end}) 
["foo", "bar", ["foo", "bar"]] 

https://hex.pm/packages/phst_transform

3

使用Tuple.to_list/1和地图具有相同功能的结果列表中,并添加备用条款对非元组输入:

defmodule A do 
    def nested_tuple_to_list(tuple) when is_tuple(tuple) do 
    tuple |> Tuple.to_list |> Enum.map(&nested_tuple_to_list/1) 
    end 
    def nested_tuple_to_list(x), do: x 
end 

{"foo", "bar", {"foo", "bar"}} |> A.nested_tuple_to_list |> IO.inspect 

输出:

["foo", "bar", ["foo", "bar"]] 

如果你想里面变换元组列表以及,你可以添加:

def nested_tuple_to_list(list) when is_list(list) do 
    list |> Enum.map(&nested_tuple_to_list/1) 
end 

这可以很容易地扩展到处理地图为好。