fibbonaci.scm 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/guile \
  2. -e main -s
  3. !#
  4. ;; use these modules to help my process the command line arguments.
  5. (use-modules (ice-9 getopt-long))
  6. (define (fibonaci n)
  7. (cond
  8. ((= n 0) 0)
  9. ((= n 1) 1)
  10. (else
  11. (+ (fibonaci (- n 1))
  12. (fibonaci (- n 2))))))
  13. ;;; (fibonaci 4)
  14. ;;; (+ (fibonaci 3) (fibonaci 2))
  15. ;;; (+ (+ (fibonaci 2) (fibonaci 1)) (+ (fibonaci 1) (fibonaci 0)))
  16. ;;; (+ (+ (fibonaci 1) (fibonaci 0)) 1 (+ 1 1))
  17. ;;; (+ (+ 1 1 1 2))
  18. ;; the following two fibonaci-iter are two iterative processes
  19. (define (fibonaci-iter n)
  20. (fib-iter 0 1 n))
  21. (define (fib-iter a b count)
  22. (if (= count 0)
  23. b
  24. (fib-iter (+ a b) a (- count 1))))
  25. (define (fibonaci-iter n)
  26. (let fib-iter ((a 0) (b 1) (count n))
  27. (if (= count 0)
  28. b
  29. (fib-iter (+ a b) a (- count 1)))))
  30. ;;This function takes a string an input and outputs a boolean.
  31. (define (inputIsNumber? x)
  32. (number? (string->number x)))
  33. (define (main args)
  34. (let* ((option-spec '((version (single-char #\v) (value #f))
  35. (help (single-char #\h) (value #f))
  36. ;;Adding in a option to specify a specific fibonacci number
  37. ;; value t means that the program expects a value, if it does not receive a value
  38. ;; then getopt-long will signal an error.
  39. ;; single char means that --number 5 == -n 5
  40. ;; predicate calls the function inputIsNumber of the string after -n or --number
  41. (number (single-char #\n) (value #t)
  42. ;;(predicate inputIsNumber?)
  43. )
  44. ))
  45. (options (getopt-long args option-spec))
  46. (help-wanted (option-ref options 'help #f))
  47. (version-wanted (option-ref options 'version #f))
  48. (number-wanted (option-ref options 'number #f)))
  49. (if (or version-wanted help-wanted number-wanted)
  50. (begin
  51. (if version-wanted
  52. (display "Fibonacci version 0.1\n"))
  53. (if help-wanted
  54. (display "\
  55. Fibonacci options [options]
  56. -v, --version Display version
  57. -h, --help Display this help
  58. -n, --number Display the nth fibonacci number.
  59. "))
  60. (if number-wanted
  61. (display (fibonaci (string->number number-wanted))))
  62. )
  63. (begin
  64. (display "Hello, World!") (newline)))))