Zero cost abstraction replacment for Elixir Enum and Stream. Faster and lower memory usage than both.
defmodule ExampleZEnum do
use ZEnum
def do_stuff(input) do
input
|> ZEnum.from_list()
|> ZEnum.map(fn x -> x * 2 end)
|> ZEnum.filter(fn x -> x <= 6 end)
end
end
ExampleZEnum.do_stuff([1, 2, 3, 4, 1, 2, 3])
# outputs [2, 4, 6, 2, 4, 6]Rather than creating an intermediate list like Enum, or using closure functions like Stream, ZEnum instead generates optimised tail call recursive functions at compile time. This gives performance of crafting hand rolled functions, but hiding the complexity and state management.
The above module gets turned into something like...
defmodule ExampleZEnum do
def do_stuff(input) do
__z_0_0_next__(input, [])
end
defp __z_0_0_next__(op_0_from_list_list, op_3_to_list_acc) do
case op_0_from_list_list do
[value | op_0_from_list_list] ->
value = (fn x -> x * 2 end).(value)
if (fn x -> x <= 6 end).(value) do
op_3_to_list_acc = [value | op_3_to_list_acc]
__z_0_0_next__(op_0_from_list_list, op_3_to_list_acc)
else
__z_0_0_next__(op_0_from_list_list, op_3_to_list_acc)
end
[] ->
Enum.reverse(op_3_to_list_acc)
end
end
endIf available in Hex, the package can be installed
by adding zenum to your list of dependencies in mix.exs:
def deps do
[
{:zenum, "~> 0.1.0"}
]
endDocumentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/zenum.