Commit | Line | Data |
---|---|---|
2de7ddb7 MG |
1 | #! /usr/local/bin/guile -s |
2 | !# | |
3 | ;;; Commentary: | |
4 | ||
5 | ;;; This is a command-line factorial calculator. Run like this: | |
6 | ;;; | |
7 | ;;; ./fact 5 | |
8 | ;;; | |
9 | ;;; to calculate the factorial of 5 | |
10 | ||
11 | ;;; Author: Martin Grabmueller | |
12 | ;;; Date: 2001-05-29 | |
13 | ||
14 | ;;; Code: | |
15 | ||
16 | (use-modules (ice-9 getopt-long)) | |
17 | ||
18 | ;; This is the grammar for the command line synopsis we expect. | |
19 | ;; | |
20 | (define command-synopsis | |
21 | '((version (single-char #\v) (value #f)) | |
22 | (help (single-char #\h) (value #f)))) | |
23 | ||
24 | ;; Display version information and exit. | |
25 | ;; | |
26 | (define (display-version) | |
27 | (display "fact 0.0.1\n")) | |
28 | ||
29 | ;; Display the usage help message and exit. | |
30 | ;; | |
31 | (define (display-help) | |
32 | (display "Usage: fact [options...] number\n") | |
33 | (display " --help, -h Show this usage information\n") | |
34 | (display " --version, -v Show version information\n")) | |
35 | ||
36 | ;; Interpret options, if --help or --version was given, print out the | |
37 | ;; requested information and exit. Otherwise, calculate the factorial | |
38 | ;; of the argument. | |
39 | ;; | |
40 | (define (main options) | |
41 | (let ((help-wanted (option-ref options 'help #f)) | |
42 | (version-wanted (option-ref options 'version #f)) | |
43 | (args (option-ref options '() '()))) | |
44 | (cond | |
45 | ((or version-wanted help-wanted) | |
46 | (if version-wanted | |
47 | (display-version)) | |
48 | (if help-wanted | |
49 | (display-help))) | |
50 | ((not (= (length args) 1)) | |
51 | (display-help)) | |
52 | (else | |
53 | (display (fact (string->number (car args)))) | |
54 | (newline))))) | |
55 | ||
56 | ;; Calculate the factorial of n. | |
57 | ;; | |
58 | (define (fact n) | |
59 | (if (< n 2) | |
60 | 1 | |
61 | (* n (fact (- n 1))))) | |
62 | ||
63 | ;; Call the main program with parsed command line options. | |
64 | ;; | |
65 | (main (getopt-long (command-line) command-synopsis)) | |
66 | ||
67 | ;; Local variables: | |
68 | ;; mode: scheme | |
69 | ;; End: |