作业说明: https://inst.eecs.berkeley.edu/~cs61a/sp21/hw/hw07/
目录Q1: Filter Lst
类似内置函数filter
(define (filter-lst fn lst)
(if (null? lst)
lst
(if (fn (car lst))
(cons (car lst) (filter-lst fn (cdr lst)))
(filter-lst fn (cdr lst))))
)
Q2: Interleave
目前还是习惯python,python好写就先写python,再翻译成scheme。
# python
def interleave(first, second):
if not first: return second
return [first[0]] + interleave(second, first[1:])
# scheme
(define (interleave first second)
(if (null? first) second
(cons (car first) (interleave second (cdr first)))))
Q3: Accumulate
参考hw02的python版 accumulate。
(define (accumulate combiner start n term)
(if (< n 1) start
(accumulate combiner (combiner start (term n)) (- n 1) term)))
Q4: Without Duplicates
先添加(car lst),再利用filter-lst过滤掉与(car lst)相等的元素。
(define (without-duplicates lst)
(if (null? lst) lst
(cons (car lst)
(without-duplicates
(filter-lst
(lambda (x) (not (= x (car lst))))
lst)))))