Search code examples
elm

String to int conversion using toInt function


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?


Solution

  • toInt can fail in parsing. You need to check it using a case statement:

    case toInt str of
      Err msg -> ... -- do something with the error message
      Ok val -> ... -- val is an Int which you can add
    

    More about Result here