The length(List) function can be used in Guards if we want to have different methods based on the length of a list , but can we use the length function for argument pattern matching of a function ?
I guess no we cant but still would love to have an expert opinion from here
Something of this sort
where list will be the argument to the method , this can save some space as we will have to write less guards to bring in polymorphism.
method(length(list)==2) do
.......
end
method(length(list)==3) do
......
end
I have used a guard but again if we are comparing in guards and we have pattern matching then we might think of combining the both and come up with something like this which is more compact and sleek.
Agreed its not a part of the language features so far but if it was it would be great
To be honest I fail to see how this is more compact and sleek.
With patterns one matches on the structure of the data. It’s explicit and describes exactly how the data should look like. Guards exist to enforce further constraints which cannot be easily expressed in a structural pattern, such as a value being an integer.
That said, your particular examples can be expressed using structural patterns (and I would argue more clearly):
def my_function([x1, x2] = list) do
# ...
end
def my_function([x1, x2, x3] = list) do
# ...
end
On the one hand you have structural matching using patterns and on the other hand you have logical matching using conditions (guards). Both are useful but serve subtly different purposes.
Mixing them is not necessarily a bad thing but from where I’m standing it’s good to know that a pattern is a pattern and a guard is a guard. I can look at a function header and know that there is no logical component to the match (such as an or) as long as there isn’t a guard clause.
I still don’t get what kind of polymorphism you are after. If you explain your intended use-case with a more complete code sample then I’m sure we can give you a proper advice.
Outside of that I am with @wolf4earth – don’t mix guards with pattern matching, they serve different purposes. You can use both at the same time though and that’s perfectly valid if you want stricter checks.