有一个库可以做到这一点以及嵌套数据的其他转换。
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