Number Parsing in PureScript

Our program demonstrates how to parse numbers from strings in PureScript. Here’s the full source code and explanation:

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)
import Data.Number as Number
import Data.Int as Int
import Data.Maybe (Maybe(..))

main :: Effect Unit
main = do
  -- With `readFloat`, we parse a string to a floating-point number
  case Number.fromString "1.234" of
    Just f -> log $ show f
    Nothing -> log "Failed to parse float"

  -- For `readInt`, we use base 10 (decimal)
  case Int.fromString 10 "123" of
    Just i -> log $ show i
    Nothing -> log "Failed to parse int"

  -- `readInt` can also parse hexadecimal numbers
  case Int.fromString 16 "1c8" of
    Just d -> log $ show d
    Nothing -> log "Failed to parse hex"

  -- There's no built-in function for parsing unsigned integers in PureScript,
  -- so we'll use `readInt` and ensure the result is positive
  case Int.fromString 10 "789" of
    Just u | u >= 0 -> log $ show u
    _ -> log "Failed to parse unsigned int"

  -- For convenience, we can use `readInt` with base 10
  case Int.fromString 10 "135" of
    Just k -> log $ show k
    Nothing -> log "Failed to parse int"

  -- Parse functions return Nothing on bad input
  case Int.fromString 10 "wat" of
    Just _ -> log "Unexpectedly parsed invalid input"
    Nothing -> log "Failed to parse invalid input, as expected"

In PureScript, we use the Data.Number and Data.Int modules for number parsing. Unlike in some other languages, PureScript’s type system and its use of Maybe make it explicit when a parsing operation might fail.

To run the program, you would typically compile it with the PureScript compiler and then run it with Node.js:

$ pulp run
1.234
123
456
789
135
Failed to parse invalid input, as expected

This example demonstrates how to parse various types of numbers from strings in PureScript, including floating-point numbers, integers, and hexadecimal numbers. It also shows how to handle potential parsing errors using the Maybe type.

Next, we’ll look at another common parsing task: URLs.