Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

84 рядки
2.5 KiB

  1. (define nil ())
  2. (define nil?
  3. (lambda (x)
  4. "Checks if the argument is nil."
  5. (= x nil)))
  6. (define last
  7. (lambda (seq)
  8. "Returns the last element of the given sequence."
  9. (if (nil? seq)
  10. seq
  11. (if (not (= (type (rest seq)) :pair))
  12. (first seq)
  13. (last (rest seq))))))
  14. (define n-times
  15. (lambda (times action)
  16. (if (<= times 0)
  17. nil
  18. (prog
  19. (eval action)
  20. (n-times (- 1 times) action)))))
  21. (define range
  22. (lambda (:keys from :defaults-to 0 to)
  23. "Returns a sequence of numbers starting with the number
  24. defined by the key 'from' and ends with the number defined in
  25. 'to'."
  26. (if (<= from to)
  27. (pair from (range :from (+ 1 from) :to to))
  28. nil)))
  29. (define map
  30. (lambda (function sequence)
  31. "Takes a sequence and a function as arguments and returns a
  32. new sequence which contains the results of using the first
  33. sequences elemens as argument to that function."
  34. (if (nil? sequence)
  35. sequence
  36. (pair (function (first sequence))
  37. (map (rest sequence) function)))))
  38. (define reduce
  39. (lambda (function sequence)
  40. "Takes a sequence and a function as arguments and applies the
  41. function to the argument sequence. This only works correctly if the
  42. given function accepts a variable amount of parameters. If your
  43. funciton is limited to two arguments, use `reduce-binary' instead."
  44. (eval (pair function sequence))))
  45. (define reduce-binary
  46. (lambda (function sequence)
  47. "Takes a sequence and a function as arguments and applies the
  48. function to the argument sequence. reduce-binary applies the
  49. arguments `pair-wise' which means it works with binary functions
  50. as compared to `reduce'."
  51. (if (nil? (rest sequence))
  52. (first sequence)
  53. (function (first sequence)
  54. (reduce-binary (rest sequence) function)))))
  55. (define filter
  56. (lambda (function sequence)
  57. (if (nil? sequence)
  58. nil
  59. (if (function (first sequence))
  60. (pair (first sequence)
  61. (filter (rest sequence) function))
  62. (filter (rest sequence) function)))))
  63. (define printf
  64. (lambda (:keys sep :defaults-to " " end :defaults-to "\n" :rest args)
  65. (if (and (nil? (first args)) (nil? (rest args)))
  66. (print end)
  67. (prog
  68. (print (first args))
  69. (if (not (nil? (rest args)))
  70. (print sep))
  71. ;; TODO(Felix): later we should use `extend' here:
  72. ;; (eval (extend (quote (printf :sep sep :end end)) (rest args)))
  73. (eval (pair printf (pair :sep (pair sep (pair :end (pair end (rest args)))))))
  74. nil))))