[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