In my Matrex project I need to define a set of functions for different data types and I need to do it serveral times.
Now I have this code, which works but looks cumbersome:
defmodule Array
[
float64: {:float, 64},
float32: {:float, 32},
byte: {:integer, 8},
int16: {:integer, 16},
int32: {:integer, 32},
int64: {:integer, 64}
]
|> Enum.each(fn {type, {spec, bits}} ->
defp list_to_binary([e | tail], unquote(type)),
do: <<e::unquote(spec)()-little-unquote(bits), list_to_binary(tail, unquote(type))::binary>>
end)
end
I want to make a macro, which would allow to do the same thing with this syntax:
deftyped list_to_binary([e | tail], type), do:
<<e::type_spec, list_to_binary(tail, type)::binary>>
So, generally I want to:
- Hide looping through types in the macro
- Use one-term binary typespec:
::typespec
instead of::unquote(spec)()-little-unquote(bits)
My last attempt is below. It compiles, but does not work.
defmacro deftyped(call, expr \\ nil) do
[
float64: {:float, 64},
float32: {:float, 32},
byte: {:integer, 8},
int16: {:integer, 16},
int32: {:integer, 32},
int64: {:integer, 64}
]
|> Enum.each(fn {type, {spec, bits}} ->
quote do
def(unquote(call), unquote(expr))
end
end)
end
Please, tell me what is possible to accomplish here and how?