Fl4m3Ph03n1x

Fl4m3Ph03n1x

Use guards on anonymous functions

Background

I have a filter to where I am passing an anonymous function. In this function I want to check that the key of the tuple I am evaluation is a string and if so return true, like in the following code:

:persistent_term.put("hello", :world)

:persistent_term.get() 
|> Enum.filter(fn {key, _val} when is_binary(key)-> true end)

Error

However, when I do so, I get an error:

** (FunctionClauseError) no function clause matching in :erl_eval."-inside-an-interpreted-fun-"/1    
    
    The following arguments were given to :erl_eval."-inside-an-interpreted-fun-"/1:
    
        # 1
        {Logger.Config.DeletedHandlers,
         [
           {:primary, %{level: :notice}},
           {:default, :logger_std_h,
            %{
              config: %{
                burst_limit_enable: true,
                burst_limit_max_count: 500,
                burst_limit_window_time: 1000,
                drop_mode_qlen: 200,
                filesync_repeat_interval: :no_repeat,
                flush_qlen: 1000,
                overload_kill_enable: false,
                overload_kill_mem_size: 3000000,
                overload_kill_qlen: 20000,
                overload_kill_restart_after: 5000,
                sync_mode_qlen: 10,
                type: :standard_io
              },
              filter_default: :stop,
              filters: [
                remote_gl: {&:logger_filters.remote_gl/2, :stop},
                domain: {&:logger_filters.domain/2, {:log, :super, [:otp, :sasl]}},
                no_domain: {&:logger_filters.domain/2, {:log, :undefined, []}}
              ],
              formatter: {:logger_formatter, %{legacy_header: true, single_line: false}},
              id: :default,
              level: :all,
              module: :logger_std_h
            }}
         ]}
    
    (stdlib) :erl_eval."-inside-an-interpreted-fun-"/1
    (stdlib) erl_eval.erl:829: :erl_eval.eval_fun/6
    (elixir) lib/enum.ex:2942: Enum.filter_list/2

What really makes this confusing is that a similar function works as expected:


:persistent_term.get()
    |> Enum.filter(fn {key, _val} -> if is_binary(key) do true else false end end)

They both do the same, except the second one works and the first one doesn’t. According to the documentation I know I can use guards in anonymous functions:

https://hexdocs.pm/elixir/master/guards.html#where-guards-can-be-used

So, it is clear to me that I am doing something wrong.

Questions

1 .What am I missing?
2. Is this the most compact way of verifying if a key is a string?

Marked As Solved

david_ex

david_ex

Enum.filter must be able to apply the given function to each individual input. In your example, that’s not the case (some inputs in the collection don’t satisfy the guard).

To fix it, add a clause matching _ that simply returns false:

:persistent_term.get() 
|> Enum.filter(fn
    {key, _val} when is_binary(key)-> true
    _ -> false
end)

Although I would personally find this more readable for what you’re trying to do:

Enum.filter(:persistent_term.get(), fn {key, _val} -> is_binary(key) end)

Also Liked

idi527

idi527

:wave:

Would that work?

:persistent_term.get() 
|> Enum.filter(fn {key, _val} -> is_binary(key) end)

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
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
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
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
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
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
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

Other popular topics Top

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
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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