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)

bobbypriambodo

bobbypriambodo

The second question can be done by using Enum.map/2 and String.to_integer/1. A nice way to exercise mapping a function through a list!

For the first question, how much of the “nature” would you want to capture? It being a:

  • two-element list? Can it have more elements?
  • two-element list of anything?
  • two-element list that are strictly equal to ["1", "2"]?
  • two-element list of strings?
  • two-element list of strings that represent integers?
  • two-element list of strings that represent integers and are strictly increasing?

It might help to expand on what you actually want.

blackode

blackode

This is very descriptive … Even I learned something how to write the code.
Thanks a lot :bouquet: :bouquet:

Where Next?

Popular in Questions 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
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
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
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
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
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
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
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
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
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

We're in Beta

About us Mission Statement