[2021 Spring] CS61A 学习笔记 Homework 7: Scheme Lists

时间:2021-07-22
本文章向大家介绍[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)))))

原文地址:https://www.cnblogs.com/ikventure/p/15043541.html