Are you sure? Because to me it looks like
{value: result.last, flag: :previous}
is going to look something like
{value: {value: item, flag: :ok}, flag: :previous}
or worse if nested even further (though maybe there is some subtlety that I’m missing).
Though some of the pattern matching could be relocated
defmodule Test do
defp new_acc(current, last, acc, check_fn) do
cond do
check_fn.(current) ->
[%{value: current, flag: :ok} | acc]
true ->
[%{value: last, flag: :previous} | acc]
end
end
defp last_true([], acc, _check_fn), do:
Enum.reverse(acc)
defp last_true([head|tail], [last|_] = acc, check_fn ), do:
last_true(tail, new_acc(head, last, acc, check_fn), check_fn)
def last_true([], _), do:
[]
def last_true([head|tail], check_fn), do:
last_true(tail, new_acc(head, nil, [], check_fn), check_fn)
end
IO.inspect Test.last_true(Enum.to_list(1..10), fn n -> rem(n,2) === 0 end)
.
[%{flag: :previous, value: nil}, %{flag: :ok, value: 2},
%{flag: :previous, value: %{flag: :ok, value: 2}}, %{flag: :ok, value: 4},
%{flag: :previous, value: %{flag: :ok, value: 4}}, %{flag: :ok, value: 6},
%{flag: :previous, value: %{flag: :ok, value: 6}}, %{flag: :ok, value: 8},
%{flag: :previous, value: %{flag: :ok, value: 8}}, %{flag: :ok, value: 10}]