silverdr

silverdr

String to existing atom unless atom already

There’s a variable, which might come as either atom or string (binary in erlang parlance). I need to use it to Access a Keyword list with atoms as keys. I surely can put a conditional around the String.to_existing_atom/1 so that I don’t get an exception when the variable is an atom already. But maybe there’s a better way to deal with such situation?

Most Liked

dimitarvp

dimitarvp

I don’t think there is such a way, you’re better off just writing two function variants for atom and binary argument.

adamu

adamu

The worst I could come up with is String.to_existing_atom(to_string(foo)) :slight_smile:

derpycoder

derpycoder

I think this is what @dimitarvp suggested:

hash_map = %{foo: "Foo", bar: "Bar"}

defmodule HashMap do
  def get(hash_map, key) when is_atom(key), do: hash_map[key]
  def get(hash_map, key) when is_binary(key), do: hash_map[String.to_existing_atom(key)]  
end

{atom, string} = {hash_map |> HashMap.get(:foo), hash_map |> HashMap.get("bar")}

# Output
# {"Foo", "Bar"}

If you pass non existent keys in, you get nil values back, no exception.


P.S. I just wrote it for practice, as I am learning Elixir.

brettbeatty

brettbeatty

If you’re only looking in a Keyword list, you could bypass the Access behaviour and do your own lookup to avoid needing to turn a string into an atom at all.

def lookup(keyword, key) when is_atom(key) do
  Keyword.get(keyword, key)
end

def lookup(keyword, key) when is_binary(key) do
  # just an example of one way to do this approach
  if pair = Enum.find(keyword, fn {k, _v} -> Atom.to_string(k) == key end) do
    elem(pair, 1)
  end
end

Where Next?

Popular in Questions Top

sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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

Other popular topics 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
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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
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
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement