wktdev

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?

Most Liked

bobbypriambodo

bobbypriambodo

And if you want to go further, let’s pattern match on the content of the string itself:

def strip_prefix("prefix" <> rest), do: rest

strip_prefix("foo") # FunctionClauseError
strip_prefix("prefixfoo") # => foo

But note that you can’t do this:

def strip_suffix(rest <> "suffix"), do: rest
# CompileError, a binary field without size is only allowed at the end of a binary pattern

You must specify the size:

def strip_suffix(<<rest::binary-size(4)>> <> "suffix"), do: rest

strip_suffix("foo") # FunctionClauseError
strip_suffix("foosuffix") # FunctionClauseError
strip_suffix("fooosuffix") # => fooo
andre1sk

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

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

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 43657 311
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31194 112
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52774 488
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement