ParseError
The ParseError type provides structured error handling for parsing operations.
Used by functions like Int.parse, Float.parse,
and BigInt.parse.
import IO
match Int.parse "42"
| Ok n -> println "Parsed: ${n}"
| Err InvalidFormat{input} -> println "Invalid format: ${input}"
| Err EmptyInput -> println "Empty input"
| Err Overflow{input} -> println "Number too large: ${input}"
See Also: Contracts
For preventing errors through preconditions and postconditions, see
Contracts. Use @pre
to validate inputs before operations that might fail.
Constructors
ParseError
type ParseError = InvalidFormat{...} | EmptyInput | Overflow{...}
| Constructor | Fields | Description |
|---|---|---|
InvalidFormat |
input: String |
The input string has an invalid format for the target type |
EmptyInput |
— | The input string is empty |
Overflow |
input: String |
The parsed value would overflow the target type |
Trait Implementations
Show
Provides human-readable error descriptions:
err = InvalidFormat{input: "abc"}
println (show err)
# => InvalidFormat: abc
println (show EmptyInput)
# => EmptyInput
Error
Implements the standard Error trait with message and kind:
| Constructor | Error Kind |
|---|---|
InvalidFormat | :invalid-format |
EmptyInput | :empty-input |
Overflow | :overflow |
Examples
Parsing User Input
parse-age = fn(input) =>
match Int.parse (String.trim input)
| Ok n if n >= 0 && n <= 150 -> Ok n
| Ok n -> Err "Age must be between 0 and 150"
| Err EmptyInput -> Err "Please enter an age"
| Err InvalidFormat{..} -> Err "Please enter a valid number"
| Err Overflow{..} -> Err "Number is too large"
Parsing with Default
parse-or-default = fn(input, default) =>
match Int.parse input
| Ok n -> n
| Err _ -> default
port = parse-or-default (Env.get "PORT") 8080
Chaining Parse Operations
parse-point = fn(x-str, y-str) =>
match (Int.parse x-str, Int.parse y-str)
| (Ok x, Ok y) -> Ok {x: x, y: y}
| (Err e, _) -> Err e
| (_, Err e) -> Err e