Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define curried data constructor via Quark.Partial.defpartial #47

Merged
merged 3 commits into from
Mar 15, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion lib/algae/internal.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,36 @@ defmodule Algae.Internal do
def data_ast(lines, %{aliases: _} = caller) when is_list(lines) do
{field_values, field_types, specs, args, defaults} = module_elements(lines, caller)

arg_count = Enum.count(args)

overridables =
Enum.map(0..arg_count, &({:new_partial, &1}))
++ [new: arg_count]
# More verbose, but clearer.
# for arity <- 0..Enum.count(args) do
# {:new, arity}
# end

args_without_defaults =
Enum.map(args, fn({:\\, [], [stripped, _]}) -> stripped end)

quote do
use Quark

@type t :: %__MODULE__{unquote_splicing(field_types)}
defstruct unquote(field_values)

defpartial new_partial(unquote_splicing(args_without_defaults)) do
struct(__MODULE__, unquote(defaults))
end

@doc "Positional constructor, with args in the same order as they were defined in"
@spec new(unquote_splicing(specs)) :: t()
def new(unquote_splicing(args)) do
struct(__MODULE__, unquote(defaults))
end

defoverridable [new: unquote(Enum.count(args))]
defoverridable unquote(overridables)
end
end

Expand Down