|
- (define nil ())
-
- (define nil?
- (lambda (x)
- "Checks if the argument is nil."
- (= x nil)))
-
- (define append
- (lambda (seq elem)
- (if (nil? seq)
- nil
- (if (not (= (type (rest seq)) :pair))
- ;; we are on the last element
- (mutate seq (pair (first seq) elem))
- (append (rest seq) elem)))))
-
- (define last
- (lambda (seq)
- "Returns the last element of the given sequence."
- (if (nil? seq)
- seq
- (if (not (= (type (rest seq)) :pair))
- (first seq)
- (last (rest seq))))))
-
- (define n-times
- (lambda (times action)
- (if (<= times 0)
- nil
- (prog
- (eval action)
- (n-times (- 1 times) action)))))
-
- (define range
- (lambda (:keys from :defaults-to 0 to)
- "Returns a sequence of numbers starting with the number
- defined by the key 'from' and ends with the number defined in
- 'to'."
- (if (<= from to)
- (pair from (range :from (+ 1 from) :to to))
- nil)))
-
- (define map
- (lambda (function sequence)
- "Takes a sequence and a function as arguments and returns a
- new sequence which contains the results of using the first
- sequences elemens as argument to that function."
- (if (nil? sequence)
- sequence
- (pair (function (first sequence))
- (map (rest sequence) function)))))
-
- (define reduce
- (lambda (function sequence)
- "Takes a sequence and a function as arguments and applies the
- function to the argument sequence. This only works correctly if the
- given function accepts a variable amount of parameters. If your
- funciton is limited to two arguments, use `reduce-binary' instead."
- (eval (pair function sequence))))
-
- (define reduce-binary
- (lambda (function sequence)
- "Takes a sequence and a function as arguments and applies the
- function to the argument sequence. reduce-binary applies the
- arguments `pair-wise' which means it works with binary functions
- as compared to `reduce'."
- (if (nil? (rest sequence))
- (first sequence)
- (function (first sequence)
- (reduce-binary (rest sequence) function)))))
-
- (define filter
- (lambda (function sequence)
- (if (nil? sequence)
- nil
- (if (function (first sequence))
- (pair (first sequence)
- (filter (rest sequence) function))
- (filter (rest sequence) function)))))
-
- (define printf
- (lambda (:keys sep :defaults-to " " end :defaults-to "\n" :rest args)
- (if (and (nil? (first args)) (nil? (rest args)))
- (print end)
- (prog
- (print (first args))
- (if (not (nil? (rest args)))
- (print sep))
- ;; TODO(Felix): later we should use `extend' here:
- ;; (eval (extend (quote (printf :sep sep :end end)) (rest args)))
- (eval (extend '(printf :sep sep :end end) (rest args)))
- nil))))
|