String to int conversion using toInt function

elm
Mahdi picture Mahdi · Dec 18, 2015 · Viewed 10.2k times · Source

I am trying to convert a string to integer using String.toInt. However, when I want to bind the result to a variable and then do some simple math with it I get this error:

Function add is expecting the 2nd argument to be:

Int

But it is:

Result String Int

How can I just extract the integer part of the result?

Answer

d13 picture d13 · Jan 24, 2016

Here's how to supply the conversion with a default value in case the parsing fails.

String.toInt "5" |> Result.toMaybe |> Maybe.withDefault 0