query
On this page

toIntBase10

lib.strings.toIntBase10

Docs pulled from | This Revision | about 1 hour ago


Parse a string as a base 10 int. This supports parsing of zero-padded integers.

Inputs

str
A string to be interpreted as an int.

Type

toIntBase10 :: string -> int

Examples

lib.strings.toIntBase10 usage example

toIntBase10 "1337"
=> 1337

toIntBase10 "-4"
=> -4

toIntBase10 " 123 "
=> 123

toIntBase10 "00024"
=> 24

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

Noogle detected

Aliases

Implementation

The following is the current implementation of this function.

toIntBase10 =
    let
      matchStripInput = match "[[:space:]]*0*(-?[[:digit:]]+)[[:space:]]*";
      matchZero = match "0+";
    in
    str:
    let
      # RegEx: Match any leading whitespace, then match any zero padding,
      # capture possibly a '-' followed by one or more digits,
      # and finally match any trailing whitespace.
      strippedInput = matchStripInput str;

      # RegEx: Match at least one '0'.
      isZero = matchZero (head strippedInput) == [];

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

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

    in
      # Error on presence of non digit characters.
      if strippedInput == null
      then throw generalError
      # In the special case zero-padded zero (00000), return early.
      else if isZero
      then 0
      # Error if parse function fails.
      else if !isInt parsedInput
      then throw generalError
      # Return result.
      else parsedInput;