Created
September 30, 2021 09:25
-
-
Save yanfeng42/1e59b4218977fad9385af51758d1a050 to your computer and use it in GitHub Desktop.
same-parity: 不借助 辅助函数的 特殊 “超纲” 写法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 基础方法 | |
(define (same-parity x . l) | |
(same-parity-adpater x l) | |
) | |
(define (same-parity-adpater x l) | |
(if (null? l) | |
(cons x l) | |
(let ((car-item (car l))) | |
(if (even? (+ car-item x)) | |
(cons x (same-parity-adpater car-item (cdr l))) | |
(same-parity-adpater x (cdr l)) | |
) | |
) | |
) | |
) | |
#| | |
> (same-parity 1 3 5 6 7) | |
|(same-parity 1 3 5 6 7) | |
|(same-parity-adpater 1 (3 5 6 7)) | |
| (same-parity-adpater 3 (5 6 7)) | |
| |(same-parity-adpater 5 (6 7)) | |
| |(same-parity-adpater 5 (7)) | |
| | (same-parity-adpater 7 ()) | |
| | (7) | |
| |(5 7) | |
| (3 5 7) | |
|(1 3 5 7) | |
(1 3 5 7) | |
> (same-parity 2 3 4 5 6 7) | |
|(same-parity 2 3 4 5 6 7) | |
|(same-parity-adpater 2 (3 4 5 6 7)) | |
|(same-parity-adpater 2 (4 5 6 7)) | |
| (same-parity-adpater 4 (5 6 7)) | |
| (same-parity-adpater 4 (6 7)) | |
| |(same-parity-adpater 6 (7)) | |
| |(same-parity-adpater 6 ()) | |
| |(6) | |
| (4 6) | |
|(2 4 6) | |
(2 4 6) | |
|# |
Author
yanfeng42
commented
Sep 30, 2021
•
; 更进一步 实现 filter. 参考 下一个题目之前的 背景介绍中 的 map 实现
(define (filter proc items)
(if (null? items)
items
(if (proc (car items))
(cons (car items) (filter proc (cdr items)))
(filter proc (cdr items))
)
)
)
(define (same-parity x . l)
(cons x (filter (lambda (item) (even? (+ item x))) l))
)
#|
> (same-parity 1 3 5 6 7)
|(same-parity 1 3 5 6 7)
| (filter #<procedure> (3 5 6 7))
| |(filter #<procedure> (5 6 7))
| | (filter #<procedure> (6 7))
| | (filter #<procedure> (7))
| | |(filter #<procedure> ())
| | |()
| | (7)
| |(5 7)
| (3 5 7)
|(1 3 5 7)
(1 3 5 7)
> (same-parity 2 3 4 5 6 7)
|(same-parity 2 3 4 5 6 7)
| (filter #<procedure> (3 4 5 6 7))
| (filter #<procedure> (4 5 6 7))
| |(filter #<procedure> (5 6 7))
| |(filter #<procedure> (6 7))
| | (filter #<procedure> (7))
| | (filter #<procedure> ())
| | ()
| |(6)
| (4 6)
|(2 4 6)
(2 4 6)
|#
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment