Fl4m3Ph03n1x

Fl4m3Ph03n1x

String to integer tuple API

Background

I want to convert a String to an integer. To this extent I know I can use one of the two following functions:

  1. String.to_integer
  2. Integer.parse

My concern

My concern here is the API. With option 1 if the string is invalid, it will just raise an exception and explode. This is not very elixiry as it forces me down to a try/rescue approach.

So the alternative would be option 2. Except the API for this function is rather inconsistent. Sometimes it will return :error other times it will just explode. Quite literally, I do not know what to expect, so I still need to use a try/rescue here as well.

Question

My objective is to have a parsing function that returns a tagged tuple for the errors. Something among the lines of {:error, reason}. Now, I know I can easily create one, but I was wondering if there is a function in Elixir that already does this.

Is there any parse function in Elixir that already returns tagged tupples when parsing data?

Marked As Solved

NobbZ

NobbZ

There is none, but you can easily wrap yourself, as I have shown in my code example.

Also Liked

jola

jola

I believe you’re misunderstanding the intent of that paragraph. It is correct that errors are not used as control flow, and that’s why the function explicitly says “must be the string representation of an integer”. The paragraph supports this, you shouldn’t wrap String.to_integer in a try. That’s the intent of the paragraph, not that errors are not used at all. Rather they should be used for “unexpected and/or exceptional situations”, such as someone passing "hello" to String.to_integer. Just like it should raise if it is passed :potato.

Elixir consistently raises ArgumentError for invalid inputs in the cases where the input doesn’t make sense at all.

Another great example of this is of course Integer.parse, which accepts any string, because it’s made specifically for unknown string inputs, while it throws an ArgumentError if the base is incorrect.

Digging deeper into the Elixir source can be helpful here, where you’ll find lots of instances of raising ArgumentError (there are also other errors used regularly, like KeyError)

jola

jola

For 1. I disagree with you, I consider it perfectly elixiry. The function is for data that you know can be parsed as an integer. You should not use it for unknown inputs. The documentation is pretty clear

string must be the string representation of an integer. Otherwise, an ArgumentError will be raised. If you want to parse a string that may contain an ill-formatted integer, use Integer.parse/1 .

What makes Integer.parse explode? It should give you either a tuple of number and remainder or :error.

Ah, I see it raises if you give it an invalid base, not because you give it an invalid string input.

hauleth

hauleth

Will you really allow user to specify base? Or you will really use base over 36? In general almost all Elixir functions can throw when passed incorrect arguments. Do you also want to prevent situation when someone passes atom to Enum.reverse/1?

Ted

Ted

I have a related question.

(Well, I think it might be related; I’m a novice and everything’s possible. :smile: )

I see that Elixir’s naming conventions discuss the trailing-bang:

A trailing bang (exclamation mark) signifies a function or macro where failure cases raise an exception.

Many functions come in pairs, such as File.read/1 and File.read!/1 . File.read/1 will return a success or failure tuple, whereas File.read!/1 will return a plain value or else raise an exception…

So, in a parallel Elixir universe, could Integer.parse not exist and instead we’d have both String.to_integer and String.to_integer!?

EDIT: hmm, maybe that parallel universe would actually be a pain; I overlooked the fact that Integer.parse accounts for remainder_of_binary and String.to_integer doesn’t.

Where Next?

Popular in Questions Top

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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
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
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
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
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

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
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
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
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
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
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
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
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
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

We're in Beta

About us Mission Statement