raytracer

raytracer

Change one field in map from string to integer?

Hello,

Elixir noob here! I’ve started a small project to learn Elixir.

I have a map:

map = %{
  id: "100"
}

The id value is a string and it needs to be converted to an integer. However the id value may already be an integer and not need converting.

Therefore I wrote this:

map = if String.valid?(map.id) do
  x = String.to_integer(map.id)
  Map.put(map, :id, x)
else
  map
end

The above code works but looks ugly! Is there a better way?

Most Liked

NobbZ

NobbZ

This will not change map.

To make it actually change the value of map you need to assign the result like this:

map = if (map.id |> is_binary), do: map |> Map.replace!(:id,100)

But we do not have an else branch, so what happens when map.id is not binary? We’ll get nil into map, thats not quite the expectation. So we need to add , else: map to make that work as well.

Also I do not think, that piping gives anything here, in fact after adding the else branch, we get another set of parens that feels placed wrong. Since both involved pipes are single “staged” its more readable (in my opinion) to just apply the function.

NobbZ

NobbZ

You can use a function and use pattern matching/guards to do this task:

def convert_id(%{id: id} = data) when is_binary(id), do: %{data | id: String.to_integer(id)}
def convert_id(%{id: id} = data) when is_integer(id), do: data

Or you can use Map.update!/3 with an anonymous function:

map = Map.update!(map, :id, fn
  id when is_binary(id) -> String.to_integer(id)
  id when is_integer(id) -> id
end)

Both approaches are untested and build in a way that they will crash when id is not parsable into an integer or already is an integer. Also both will crash when there is no key :id in the map.

But why does this happen at all? A much better approach were to build the system in a way that the id is always an integer.

digoio

digoio

Yeah, I’m a noob also and just punched that into iex. OK, how’s this?

map =  case (map.id |> is_binary) do
               true -> Map.replace!(map,:id,100)
               false -> map
            end

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
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
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
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

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
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
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
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
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
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
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