What do you mean?
defmodule Example do
def sample(data, value, keys \\ [:list_a, :list_b, :list_c]),
do: data |> Map.take(keys) |> Enum.find(&do_sample(&1, value))
defp do_sample({_key, list}, value) when is_list(list), do: value in list
end
defmodule ListStruct do
defstruct [:list_a, :list_b, :list_c]
end
Example.sample(%ListStruct{list_a: [1, 2, 3], list_b: [4, 5, 6], list_c: [7, 8, 9]}, 5)
{:list_b, [4, 5, 6]}
For me it’s working well.
Sorry, did you mean that you tried to do:
Example.sample(%ListStruct{list_a: nil, list_b: [4, 5, 6], list_c: nil}, 5)
If so then there are 3 solutions (depends on use case):
# 1. change struct definition:
defstruct [:list_a, :list_b, :list_c]
# to
defstruct [list_a: [], list_b: [], list_c: []]
# 2. use keys enforcing which prevents to create struct with nil values
@enforce_keys [:list_a, :list_b, :list_c]
# in such case this would fail at compile time:
%ListStruct{list_a: nil, list_b: [4, 5, 6], list_c: nil}
# 3. add extra guard:
defmodule Example do
def sample(data, value, keys \\ [:list_a, :list_b, :list_c]),
do: data |> Map.take(keys) |> Enum.find(&do_sample(&1, value))
defp do_sample({_key, nil}, value), do: false
defp do_sample({_key, list}, value) when is_list(list), do: value in list
end