Number Parsing in Scheme

(import (scheme base)
        (scheme write))

; With string->number, we can parse floating-point numbers
(define f (string->number "1.234"))
(display f)
(newline)

; string->number can also parse integers
(define i (string->number "123"))
(display i)
(newline)

; Hexadecimal numbers can be parsed by specifying the radix
(define d (string->number "0x1c8" 16))
(display d)
(newline)

; There's no built-in function for parsing unsigned integers in Scheme,
; but we can use string->number for positive integers
(define u (string->number "789"))
(display u)
(newline)

; string->number is a general function that can parse both integers and floats
(define k (string->number "135"))
(display k)
(newline)

; string->number returns #f for invalid input
(define e (string->number "wat"))
(display e)
(newline)

In Scheme, number parsing is primarily done using the string->number function. This function is versatile and can handle various number formats, including integers, floating-point numbers, and even numbers in different bases.

Here’s a breakdown of the number parsing operations:

  1. Parsing floating-point numbers: The string->number function can parse floating-point numbers directly.

  2. Parsing integers: string->number also handles integer parsing without needing to specify a base for decimal numbers.

  3. Parsing hexadecimal numbers: To parse hexadecimal numbers, we use string->number with a radix of 16.

  4. Parsing unsigned integers: Scheme doesn’t have a separate type for unsigned integers. We can use string->number for positive integers.

  5. Convenience parsing: string->number serves as a general-purpose function for parsing both integers and floating-point numbers.

  6. Error handling: When given invalid input, string->number returns #f (false) instead of raising an error.

To run this Scheme program, save it to a file (e.g., number-parsing.scm) and use your Scheme interpreter. For example, if you’re using Chez Scheme:

$ scheme --script number-parsing.scm
1.234
123
456
789
135
#f

Note that the exact output format may vary slightly depending on your Scheme implementation.