fact 1.6 KB

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