Command Line Arguments in Scheme

Command-line arguments are a common way to parameterize execution of programs. For example, scheme hello.scm uses hello.scm as an argument to the scheme program.

(define (main args)
  ; args provides access to raw command-line arguments.
  ; Note that the first value in this list is the path to the program,
  ; and (cdr args) holds the arguments to the program.
  (define args-with-prog args)
  (define args-without-prog (cdr args))

  ; You can get individual args with normal list indexing.
  (define arg (list-ref args 3))

  (display args-with-prog)
  (newline)
  (display args-without-prog)
  (newline)
  (display arg)
  (newline))

; Call the main function with command-line arguments
(main (command-line-arguments))

To experiment with command-line arguments, it’s best to save this code in a file (e.g., command-line-arguments.scm) and run it using your Scheme interpreter.

$ scheme command-line-arguments.scm a b c d
(command-line-arguments.scm a b c d)
(a b c d)
c

In Scheme, we define a main function that takes the command-line arguments as a parameter. The command-line-arguments procedure is used to get the list of arguments when the program is run.

Unlike Go, Scheme doesn’t have a built-in way to exclude the program name from the arguments list, so we manually create args-without-prog by using cdr to get all but the first element of the list.

To get an individual argument, we use list-ref instead of array indexing. Remember that Scheme uses 0-based indexing, so (list-ref args 3) will give us the fourth argument.

Finally, we use display and newline to print the results, which is similar to fmt.Println in Go.

Next, we’ll look at more advanced command-line processing with option parsing libraries available in Scheme.