我有一个作业,我需要计算输入中的对数.
这是我到目前为止:
(define x 0)
(define number-of-pairs
(lambda (v)
(if (pair? v)
(+ x 1)
(+ x 0))))
Run Code Online (Sandbox Code Playgroud)
然后我用它如下:
(number-of-pairs (cons (cons 'a 'b) 'c))
Run Code Online (Sandbox Code Playgroud)
它应该产生2,但它产生1,因为它只通过函数一次.如果我试试
(number-of-pairs 10)
Run Code Online (Sandbox Code Playgroud)
因为没有对,所以它会产生0.
你必须考虑两种情况:
对于第二种情况,我们可以在总数中加一,因为我们知道当前元素是一对,然后我们在该对的两个部分调用递归 - 因为我们不知道它们中的任何一个是否在转一对.
以下是需要做什么的总体思路,填写空白:
(define (number-of-pairs v)
(if (not (pair? v))
<???>
(+ <???>
(number-of-pairs <???>)
(number-of-pairs <???>))))
Run Code Online (Sandbox Code Playgroud)
使用这些示例来测试您的过程:
(number-of-pairs 10)
> 0
(number-of-pairs (cons (cons 'a 'b) 'c))
> 2
(number-of-pairs '(a b c))
> 3
(number-of-pairs (cons 'a (cons 'b (cons (cons 'c (cons (cons 'd '()) '())) '()))))
> 6
Run Code Online (Sandbox Code Playgroud)