wktdev
Question regarding pattern matching functions based on input type
I understand pattern matching in a very basic sense.
So for example I understand perfectly well what this code does
%{william: age} = %{william: 40 }
IO.inspect age # 40
{a, b} = {100, 200}
IO.inspect a # 100
IO.inspect b # 200
What I am having trouble understanding is function behavior when named functions with the same name and arity take precedence over one another based on argument type
So for example, the following code is an implementation of a len function and it returns the length of a list. For the most part I understand how it works ( I think ). The two functions allow for behavior usually reserved for conditional statements. If the array is empty then the recursion is terminated
defmodule Mylist do
def len(), do: 0
def len([head|tail]), do: 1 + len(tail)
end
IO.inspect Mylist.len([5, 4, 3, 2, 1]) # 5
The previous functions only work if the argument type is a list. If I did the following I get an error:
IO.inspect Mylist.len(“blah”) # no function clause matching in Mylist.len/1
Based on this, I assume there is a way to write functions that only respond to inputs that are of type number or string. Is this possible without using conditional statements?
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security










First 4 of 4 Posts
andre1sk
It possible to do using guard clause e.g.
def blah(a) when is_integer(a) , do: a
https://hexdocs.pm/elixir/master/guards.html
wktdev
Cool, thanks. I read about guard clauses but didn’t think to use them. I’m trying to learn to “think” like an Elixir dev
OvermindDL1
You can also match on the string type (binary) itself.
For integers, like andre1sk’s example, a guard clause is required (and there are guard clauses for
is_binary/1too).bobbypriambodo
And if you want to go further, let’s pattern match on the content of the string itself:
But note that you can’t do this:
You must specify the size: