query
On this page

toInt

lib.strings.toInt

Docs pulled from | This Revision | about 1 hour ago


Parse a string as an int. Does not support parsing of integers with preceding zero due to ambiguity between zero-padded and octal numbers. See toIntBase10.

Inputs

str
A string to be interpreted as an int.

Type

toInt :: string -> int

Examples

lib.strings.toInt usage example

toInt "1337"
=> 1337

toInt "-4"
=> -4

toInt " 123 "
=> 123

toInt "00024"
=> error: Ambiguity in interpretation of 00024 between octal and zero padded integer.

toInt "3.14"
=> error: floating point JSON numbers are not supported

Noogle detected

Aliases

Implementation

The following is the current implementation of this function.

toInt =
    let
      matchStripInput = match "[[:space:]]*(-?[[:digit:]]+)[[:space:]]*";
      matchLeadingZero = match "0[[:digit:]]+";
    in
    str:
    let
      # RegEx: Match any leading whitespace, possibly a '-', one or more digits,
      # and finally match any trailing whitespace.
      strippedInput = matchStripInput str;

      # RegEx: Match a leading '0' then one or more digits.
      isLeadingZero = matchLeadingZero (head strippedInput) == [];

      # Attempt to parse input
      parsedInput = fromJSON (head strippedInput);

      generalError = "toInt: Could not convert ${escapeNixString str} to int.";

    in
      # Error on presence of non digit characters.
      if strippedInput == null
      then throw generalError
      # Error on presence of leading zero/octal ambiguity.
      else if isLeadingZero
      then throw "toInt: Ambiguity in interpretation of ${escapeNixString str} between octal and zero padded integer."
      # Error if parse function fails.
      else if !isInt parsedInput
      then throw generalError
      # Return result.
      else parsedInput;