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

OvermindDL1

OvermindDL1

You can also match on the string type (binary) itself. :slight_smile:

def takes_only_string(<<the_string::binary>>), do: the_string

For integers, like andre1sk’s example, a guard clause is required (and there are guard clauses for is_binary/1 too). :slight_smile:

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
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
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
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
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement