Scheme-检索数字中出现的数字
我正在进行bert方案练习,这项练习让我很难接受: 示例:(n-发生544555 5)=>4 你知道怎么数数吗 我的想法是:Scheme-检索数字中出现的数字,scheme,Scheme,我正在进行bert方案练习,这项练习让我很难接受: 示例:(n-发生544555 5)=>4 你知道怎么数数吗 我的想法是: (define (occurences d n) (if (equal? (remainder d 10) n) (add1 (occurences (quotient d 10) n)) (occurences (quotient d 10) n) )) 因此,在例如1223 2的示例中,它将: 检查3是否等于2 说不
(define (occurences d n)
(if (equal? (remainder d 10) n)
(add1 (occurences (quotient d 10) n))
(occurences (quotient d 10) n)
))
因此,在例如1223 2的示例中,它将:
您缺少递归的基本情况;如果d为0,则需要停止。你把n和d混淆了好几次:
(define (occurences d n)
(if (= 0 d)
(if (= 0 n) 1 0) ; base case
(if (= (remainder d 10) n)
(add1 (occurences (quotient d 10) n))
(occurences (quotient d 10) n))))
测试:
> (occurences 544555 5)
4
参数(d和n)演变如下:
d=544555 n=5
d=54455 n=5
d=5445 n=5
d=544 n=5
d=54 n=5
d=5 n=5
d=0 n=5
在边缘情况下,此操作将失败:
(出现次数0)
应返回1
,但返回的是0
。