[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)))))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM