rcm765

rcm765

Writing a keyword list guard?

I’d like a guard to determine if the value is a keyword list or not. I’ve tried the following macro:

defmacro is_keyword([{key, _value} | _tail]), do: quote do: is_atom(unquote(key))

but when I pass in a keyword list I get this error: ** (FunctionClauseError) no function clause matching in is_keyword/1

however if I remove the pattern matching in the function signature everything seems to work ok. So I’m lead to believe that pattern matching isn’t permitted in guards. If that’s the case how best can I write a single guard for keyword list detection? (yeah I know it should be a recursive function)

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

But in only works that way in guards for fixed compile time lists. It doesn’t work with runtime lists.

EDIT: Elaborating a bit now that I’m not on mobile.

You can do:

def foo(x) when x in [1,2,3] do

which will turn into

def foo(x) when x == 1 or x == 2 or x ==3 do

but what you can’t do is:

def foo(x, list) when x in list do
jhogberg

jhogberg

Erlang Core Team

No, the restriction is artificial. User-defined guards running arbitrary code would not be difficult to support from a technical point of view (we already do it, see prim_eval.S and its interaction with :erl_eval), it’s just very annoying to define what’s supposed to happen in corner cases like such a guard running a receive while in a receive, how exception tracing is supposed to work, and the likes.

So why don’t we support it?

Partially because it’s a bit of a footgun. If you end up throwing a user-defined guard into an infinite loop, which specific clause was it “called from?” If you accidentally make it side-effecting, which combination of the (say) three hidden invocations derailed things?

The main reason however is historical and there’s been no pressing need to change it. You can case over the result in the function body, and that’s been enough so far.

christhekeele

christhekeele

This is a non-starter (there is a reason the language doesn’t come with one).

TL;DR:
You cannot reliably fully traverse a list fast enough to be viable in guards.
As such, you cannot exhaustively ensure every item of a list is a Keyword pair in a guard.


Keyword lists are just lists (of atom/any two-tuples {atom, term}), which are singly-linked car/cons cells that require O(n) time to traverse.

Matches and guards are required to have near-constant-time access to data structures, since they are used in places in the VM with tight performance requirements (like selecting a function head to invoke from many given certain arguments).

This is why tuple and map indexing are allowed in guards (with integer-based elem(tuple, n) and key-based is_map_key(map, key) or :erlang.map_get(map, key)), their structures offer constant-time access to the data they compose. (Also why you can destructure on them in matches.)

I say “near” constant-time because you are also allowed to “peek” into the heads of O(n)-traversable data structures when such an operation is known to be fast and bounded (with hd in guards for lists, binary_part in guards for binaries, and destructuring in match patterns: [first | rest] for lists, "start" <> rest for strings, <<leading, rest::binary>> for binaries).

In practice this peeking is just enough to enable function clauses to recursively consume these O(n) datastructures piece-by-piece, using matching and guards to decide how to handle each chunk. Useful enough, we make concessions on the constant-time constraint.

However, fully accessing every item in a list is an unbounded operation, so, not allowed—even a theoretical “recursive” implementation (that guards are, by design, not expressive enough to support).

What your original macro (and what @Schultzer’s guard) attempts to do is just evaluate the first “peeked” term of a list for Keyword-iness, which could be useful in some contexts, but is generally insufficient to ensure that every item in a list is a keyword pair. And you can’t traverse every item in a list in guards, for reasons explained above.

LostKobrakai

LostKobrakai

To follow up on @jhogberg answer of this not being true: length/1 is a guard and completes in linear time by my understanding.

eksperimental

eksperimental

I would say it is doable. You can mimic what the Kernel.in/2 operator does. Instead of checking for values you check for every element in the list being 2-element tuple and the first element being an atom (all operations allowed in guards). If the context of the call is not a match or a guard, you delegate to Keyword.keyword?/1.

Here’s the in/2 implementation: elixir/lib/elixir/lib/kernel.ex at v1.18.4 · elixir-lang/elixir · GitHub

What you end up doing is building are nested conditions similar to this

but with :erlang.andalso/2.

Where Next?

Popular in Questions Top

itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
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
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
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
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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
Tee
can someone please explain to me how Enum.reduce works with maps
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
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement