acrolink

acrolink

How to check if a variable is a list of the nature ["1", "2"]?

And how to convert the above list to [1, 2] (i.e. to list of integers). Thank you.

Most Liked

NobbZ

NobbZ

If you want to check if all elements of a list do have a certain attribute, you can use Enum.all?, to check if something is a binary you can use is_binary/1.

So to check if all items in a list are binarys you can do the following:

iex(1)> list1 = ["1", "2"]
["1", "2"]
iex(2)> list2 = [:a, "1"]
[:a, "1"]
iex(3)> Enum.all?(list1, &is_binary/1)
true
iex(4)> Enum.all?(list2, &is_binary/1)
false

Next we will do the conversion, you asked for. String.to_integer/1 do what you have asked for directly, but will raise as soon as they hit the first string that does not represent a number.

Therefore we do also have Integer.parse/2. It does either return a tuple or :error, whenever you get :error you do not have a valid integer in the string, but as soon as you get a tuple, you know, that at least your string was prefixed by something that represents the integer in the first element of the tuple. Depending on your needs, you do want to check if the second element (remainder) is equal to "", to ensure, that there was nothing behind the number.

So to convert a list and also check if all elements could be converted, I’d do something like this:

# untested
def check_and_convert_list(list) do
  parsed_list = Enum.map(list, &Integer.parse/1) # [{1, ""}, {2, ""}]

  valid = Enum.all?(parsed_list, fn ({_, ""}) -> true
                                    (_)       -> false
                                 end)

  if valid do
    Enum.map(parsed_list, fn ({x, _}) -> x end)
  else
    :error
  end
end
Eiji

Eiji

Use Enum or Stream to map a List and for each element use &String.to_integer/1 and for @spec use String.t like in &String.to_integer/1 method.

blackode

blackode

list = ["1","2","3"]
list |> Enum.map(&String.to_integer/1)

Last Post!

bbense

bbense

It’s overkill for this problem, but I’ve written a library that solves the “is this similar to X” problem based on a single instance of X. i.e. it defines “types” based on a single instance and a definition of similar.

You give it a single instance and it returns a function that returns true or false given any other term
based on whether the term is in the same similarity class. I’ve defined 3 classes so far, congruent, similar and exact.

It’s still a work in progress and in this case it would probably match things you don’t care about since it treats all Strings as similar. i.e. [“a”,“b”] would be an exact similarity to [“1”,“2”].

The real intended use was for deeply nested data structures.

Some samples from my tests below.

https://github.com/philosophers-stone/phenetic/blob/master/test/phst_phenetic_test.exs

Where Next?

Popular in Questions Top

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
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
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
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

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
New
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 31494 112
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40042 209
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

We're in Beta

About us Mission Statement