我是Racket的新手,我正在试图找出插入排序。这就是我所拥有的,但我收到了一个错误,我无法从调试中弄明白。
let encode = function (x) {
function _enc(x, lst) {
if (typeof x !== 'object')
return x;
let i = lst.indexOf(x);
if (i >= 0)
return {'->': i};
lst.push(x);
let y = {};
for (let k of Object.keys(x))
y[k] = _enc(x[k], lst)
return y;
}
return JSON.stringify(_enc(x, []));
};
//////
let ones = [1];
ones[1] = ones;
let ones_ = [1];
ones_[1] = ones_;
console.log(encode(ones) === encode(ones_))
// more interesting example
a = {
b: {
c: 123
}
};
a.b.d = a;
a.x = [9, a.b];
a2 = {
b: {
c: 123
}
};
a2.b.d = a2;
a2.x = [9, a2.b];
console.log(encode(a) === encode(a2))
答案 0 :(得分:0)
以下功能工作:
(define (insert n l cmp (ol '()))
(cond
[(empty? l)
(append ol (list n))] ; or: (reverse (cons n (reverse ol)))
[(not (cmp n (first l)))
(append ol (list n) l)]
[else (insert n
(rest l)
cmp
(append ol (list (first l))) ; or: (reverse (cons (first l) (reverse ol)))
)] ))
(define (isort l cmp (sl '()))
(cond
[(empty? l) sl]
[else (isort (rest l)
cmp
(insert (first l)
sl
cmp))] ))
这些函数似乎是尾递归的。
测试:
(isort '(4 2 5 8 1 4 7 3 6 9) >)
(isort '(4 2 5 8 1 4 7 3 6 9) <)
输出:
'(1 2 3 4 4 5 6 7 8 9)
'(9 8 7 6 5 4 4 3 2 1)
答案 1 :(得分:0)
在insert
中使用insertionSort
时,您已“翻转”(define (insertionSort L1 cmp)
(cond
((null? L1) L1)
(else (insert cmp (insertionSort (cdr L1) cmp) (car L1)))))
的参数;它应该是
iterator.next()