Number Parsing in Racket
Racket provides built-in functions for parsing numbers from strings. The string->number
function is the primary tool for this task.
With string->number
, we can parse both floating-point and integer numbers. The function takes an optional second argument to specify the radix for integer parsing.
For parsing floating-point numbers, we simply pass the string to string->number
:
For parsing integers, we can use string->number
without specifying a radix, which defaults to 10:
string->number
will recognize hex-formatted numbers when given a radix of 16:
For parsing unsigned integers, we can use the same function:
string->number
is a general function for parsing numbers:
Unlike the Go version, which returns an error on bad input, string->number
returns #f
(false) when it can’t parse the input:
To run the program, save it as number-parsing.rkt
and use the racket
command:
This example demonstrates how to parse various types of numbers from strings in Racket. The string->number
function provides a unified interface for parsing both floating-point and integer numbers, with support for different bases.