1. 程式人生 > 其它 >[2021 Spring] CS61A 學習筆記 Homework 7: Scheme Lists

[2021 Spring] CS61A 學習筆記 Homework 7: Scheme Lists

[2021 Spring] CS61A 學習筆記 Homework 7: Scheme Lists

作業說明: 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)))))