We have the beginning of a stdlib and can parse keyword and rest args
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
(define nil ())
|
||||
|
||||
(define nil?
|
||||
(lambda (x)
|
||||
"Checks if the argument is nil."
|
||||
(= x nil)))
|
||||
|
||||
(define append
|
||||
(lambda (obj sequence)
|
||||
(if (nil? sequence)
|
||||
(list obj)
|
||||
(if (nil? (rest sequence))
|
||||
))))
|
||||
|
||||
(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 (pair printf (pair :sep (pair sep (pair :end (pair end (rest args)))))))
|
||||
nil))))
|
||||
Reference in New Issue
Block a user