(define (filter-lst fn lst)
(cond ((null? lst) '())
((fn (car lst)) (cons (car lst) (filter-lst fn (cdr lst))) )
(else (filter-lst fn (cdr lst))
)
)
)
;;; Tests
(define (even? x)
(= (modulo x 2) 0))
(filter-lst even? '(0 1 1 2 3 5 8))
; expect (0 2 8)
(define (interleave first second)
(cond ((null? first) second )
; ((null? second) first)
(else (cons (car first) (interleave second (cdr first))))
)
)
(interleave (list 1 3 5) (list 2 4 6))
; expect (1 2 3 4 5 6)
(interleave (list 1 3 5) nil)
; expect (1 3 5)
(interleave (list 1 3 5) (list 2 4))
; expect (1 2 3 4 5)
(define (accumulate combiner start n term)
(cond ((= n 0) start )
(else (accumulate combiner (combiner (term n) start) (- n 1) term))
)
)
(define (no-repeats lst)
(if (null? lst) lst
(cons (car lst)
(no-repeats (filter (lambda (x) (not (= (car lst) x))) (cdr lst))))
)
)
CS 61A HW07
最新推荐文章于 2024-09-17 23:15:58 发布
文章展示了几个Lisp函数的定义和测试用例。filter-lst函数用于基于给定条件过滤列表;even?是一个判断数字是否为偶数的辅助函数;interleave函数将两个列表交错合并;accumulatecombiner实现累加操作;最后,no-repeats函数用于从列表中去除重复元素。
摘要由CSDN通过智能技术生成