The Ndim
lib provides functions for working with n-dimensional lists.
This module is particularly useful when you need to:
- Map functions over deeply nested lists at a specific level while maintaining their shape
- Transform between the n-dimensional list and the coordinated map
If available in Hex, the package can be installed
by adding ndim
to your list of dependencies in mix.exs
:
def deps do
[
{:ndim, "~> 0.1.0"}
]
end
d2map/2
...d5map/2
- Map a function over a 2-dimensional list (upto 5-dimensional list)dmap/3
- The general version which maps a function over elements at any specified dimensional listto_coord_map/1
- Transform a n-dimensional list to a coordinate map
An n-dimensional list is a regularly nested list structure where n represents the depth of nesting. Each level must maintain consistent structure:
[1, 2, 3]
[
[1, 2, 3],
[4, 5, 6]
]
[
[
[1, 2], [3, 4]
],
[
[5, 6], [7, 8]
]
]
A coordinate map is a map representation of an n-dimensional list where each value is keyed by its dimensional coordinates. This is useful for sparse data or when you need direct coordinate access:
[
[1, 2], --> %{{0, 0} => 1, {0, 1} => 2,
[3, 4] {1, 0} => 3, {1, 1} => 4}
]
[
[[1, 2]], --> %{{0, 0, 0} => 1, {0, 0, 1} => 2,
[[3, 4]] {1, 0, 0} => 3, {1, 0, 1} => 4}
]
Map a function over a 2-dimensional list
iex> numbers = [[1, 2], [3, 4]]
iex> Ndim.d2map(numbers, fn x -> x * 2 end)
[[2, 4], [6, 8]]
Map a function over a n-dimensional list, with specified dimension, which is 3
iex> nested = [[["a", "b"], ["c", "d"]], [["e", "f"], ["g", "h"]], [["i", "j"], ["k", "l"]]]
iex> Ndim.dmap(nested, 3, &String.upcase/1)
[[["A", "B"], ["C", "D"]], [["E", "F"], ["G", "H"]], [["I", "J"], ["K", "L"]]]
Transform a 2-dimensional list to a coordinate map
iex> vector = [[1, 2], [3, 4]]
iex> Ndim.to_coord_map(vector)
%{{0, 0} => 1, {0, 1} => 2, {1, 0} => 3, {1, 1} => 4}
Find the document at https://hexdocs.pm/ndim