wktdev

wktdev

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?

Showing Posts 1 to 4

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 OP

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:

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
— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews