我在用球拍学习计划。我做了下面的程序,但它带来了一个违反合同的错误。
预期:(精确-非负-整数?)->。任何/c):'()
程序在一个间隔内查找所有数字的列表,这些数字可以被3或5整除。
#lang racket
;;Global Definitions
(define upper-bound 10)
(define lower-bound 0)
;;set-bounds: Int, Int -> ()
(define (set-bounds m n)
(set! upper-bound (max m n))
(set! lower-bound (min m n)))
;;get-numbers: () -> (Int)
(define (get-numbers)
(build-list upper-bound '()))
;;make-list: Int, (Int) -> (Int)
(define (build-list x y)
(cond
[(= x lower-bound) y]
[(= (modulo x 5) 0) (build-list (sub1 x) (cons x y))]
[(= (modulo x 3) 0) (build-list (sub1 x) (cons x y))]
[else (build-list (sub1 x) y)]))编辑:我做了奥斯卡·洛佩兹建议的修改。
发布于 2016-10-11 05:28:43
另一种方法是使用for/list创建列表:
(define (build-list ub lst)
(for/list ((i (range lb ub))
#:when (or (= 0 (modulo i 3))
(= 0 (modulo i 5))))
i))用法:
(define lb 0)
(build-list 10 '())输出:
'(0 3 5 6 9)编辑:
实际上,这里不需要第一步:
(define (build-list ub)
(for/list ((i (range lb ub))
#:when (or (= 0 (modulo i 3))
(= 0 (modulo i 5))))
i))所以你可以打电话:
(build-list 10)下面是对递归方法的修改(使用'named let'):
(define (build-list2 ub)
(let loop ((x ub) (lst '()))
(cond
[(= x lb) lst]
[(= (modulo x 5) 0) (loop (sub1 x) (cons x lst))]
[(= (modulo x 3) 0) (loop (sub1 x) (cons x lst))]
[else (loop (sub1 x) lst)])))此外,如果始终必须使用空list '()调用函数,则可以将其作为默认值放在参数列表中:
(build-list x (y '()))然后您可以使用简化的命令进行调用:
(build-list 10)发布于 2016-10-11 03:59:40
您应该首先测试递归停止的条件,即当x等于lower-bound时
(define (build-list x y)
(cond
[(= x lower-bound) y]
[(= (modulo x 5) 0) (build-list (sub1 x) (cons x y))]
[(= (modulo x 3) 0) (build-list (sub1 x) (cons x y))]
[else (build-list (sub1 x) y)]))https://stackoverflow.com/questions/39969947
复制相似问题