【发布时间】:2017-01-07 11:06:44
【问题描述】:
我正在尝试修改 http://home.adelphi.edu/~siegfried/cs270/270rl10.html 上的排序代码,我将 let 用于插入函数:
(define (mysort alon )
(let insert ((n n) (alon alon))
(cond
[(empty? alon) (cons n empty)]
[else (cond
[(< n (first alon)) (cons n alon)]
[else (cons (first alon)
(insert n (rest alon))])])
(cond
[(empty? alon) empty]
[(cons? alon) (insert (first alon)
(mysort (rest alon)))])))
(mysort (list 1 2 3 4 5 6 2 3 1 4 5 2 10))
但是,它在“let”变量声明的级别上不起作用:
n: unbound identifier in module in: n
我在这里 (https://docs.racket-lang.org/reference/let.html) 看到“让”需要具有变量的初始值。我们可以在不初始化变量的情况下使用'let'吗?上面的代码如何改正?
编辑:我尝试使用 lambda 但它不起作用:
(define (mysort4 alon )
(let ([insert4
(lambda (n alon)
(cond
[(empty? alon) (cons n empty)]
[(< n (first alon)) (cons n alon)]
[else (cons (first alon)
(insert4 n (rest alon) ))]))])
(cond
[(empty? alon) empty]
[(cons? alon) (insert4 (first alon)
(mysort4 (rest alon) ) )])))
(mysort4 (list 1 2 3 4 5 6 2 3 1 4 5 2 10))
错误是:
insert4: unbound identifier in module in: insert4
【问题讨论】:
-
命名
let没有变量的初始值将只是一个lambda。 -
我无法在上面的代码中插入 lambda 关键字。 "(let insert (lambda (n alon") 和 "(let insert lambda (n alon") 都不起作用。
-
"(let ([insert4 (lambda (n alon) ... ])" 也不起作用。