vecfun.scm 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. ;;; vecfun: an example Pre-Scheme program
  2. ;; FIXME: bodge to support static init from main
  3. (define %static-init (external "vecfun_init" (=> () null)))
  4. ;; vec-a is computed at compile-time
  5. (define %vec-a (vector-unfold (lambda (i)
  6. (* i i))
  7. 5))
  8. ;; take vec-a's length at compile-time
  9. (define %len-a (vector-length %vec-a))
  10. (define (main)
  11. (define out (current-output-port))
  12. ;; XXX: We need to run static-init to initialize vec-a, otherwise the
  13. ;; following code will segfault. The Scheme 48 VM gets around this by
  14. ;; using a hand-coded C main which runs the init routine before
  15. ;; calling the Pre-Scheme entrypoint.
  16. (%static-init)
  17. (write-string "Print vec-a with vector-for-each:\n" out)
  18. (vector-for-each (lambda (i val)
  19. (write-string " vec-a[" out)
  20. (write-integer i out)
  21. (write-string "] = " out)
  22. (write-integer val out)
  23. (newline out))
  24. %vec-a %len-a)
  25. (write-string "Print the last value of vec-a with vector-fold:\n" out)
  26. (let ((last (vector-fold (lambda (i res val)
  27. val)
  28. -1 %vec-a %len-a)))
  29. (write-string " vec-a[-1] = " out)
  30. (write-integer last out)
  31. (newline out))
  32. (write-string "Compute the sum of two vectors with vector-map:\n" out)
  33. (let ((sums (vector-map (lambda (i val1 val2)
  34. (+ val1 val2))
  35. %vec-a %len-a
  36. %vec-a %len-a)))
  37. (vector-for-each (lambda (i val)
  38. (write-string " sums[" out)
  39. (write-integer i out)
  40. (write-string "] = " out)
  41. (write-integer val out)
  42. (newline out))
  43. sums %len-a)
  44. (deallocate sums))
  45. (write-string "Build a vector of strings with vector-map:\n" out)
  46. (let ((strs (vector-map (lambda (i val)
  47. (string-repeat "x" val))
  48. %vec-a %len-a)))
  49. (vector-for-each (lambda (i val)
  50. (write-string " strs[" out)
  51. (write-integer i out)
  52. (write-string "] = \"" out)
  53. (write-string val out)
  54. (write-char #\" out)
  55. (newline out))
  56. strs %len-a)
  57. (vector-for-each (lambda (i val)
  58. (deallocate val))
  59. strs %len-a)
  60. (deallocate strs))
  61. 0)