Elixir function clauses: list of strings vs list of numbers vs tuple of strings vs tuple of numbers

StackOverflow https://stackoverflow.com/questions/23622542

  •  21-07-2023
  •  | 
  •  

Question

I want to specify 4 clauses for an Elixir function with the following patterns: i) list of strings ii) list of numbers iii) tuple of strings iv) tuple of numbers

How would I do that?

Was it helpful?

Solution

Something like this probably:

def foo([]),                      do: :empty
def foo([h|t]) when is_binary(h), do: :list_of_strings
def foo([h|t]) when is_number(h), do: :list_of_numbers
def foo(tuple) when is_tuple(tuple) do
  # Convert tuple to list of stuff, then recursively call foo
  tuple |> tuple_to_list |> foo
end

The last clause assumes you don't care about getting a tuple back from foo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top