I want to write a guard or use an existing method to use as a guard to check for a list of string. Is there any built in function for this?
@Manukam just to make sure I understand, you want to validate that all entries of a list are a string? If so, there is not a guard clause for this, you’ll need to use a conditional like
One thing you can do, depending on how you’re processing the list, is destructure and use a guard on the first element.
def some_fun([head | rest]) when is_binary(head) do
# … prob some recursive call with rest
Not all elements, if I can just check the first element that would be enough. Basically, I have few functions and want to make sure that correct function is called depending on the params. I want to execute one function when the params are a list of Structs, and another function when the params are a list of Strings
This actually works, how would I access the full list after splitting it like this in the params?
def([head | _] = list) when is_binary(head)
Edit: one thing I’ll add, if it’s possible, your code will generally be clearer if you do your matching in a function that handles a single element, and then your code handling the list doesn’t have to care if it’s a list of strings, structs, or a mix.
I guess they want to “run this on all elements if its strings” rather than “for each element, run this if it is a string, run that otherwise”.
Yep, I think you’re right. In my experience though, that pattern can sometimes be refactored into functions dealing with collections and functions dealing with elements, and it usually makes for easier to understand and more robust code.
defguard is_head_binary(list) when is_binary(hd(list))