[英]Spliting a list at a certain location using Racket/Scheme
我正在尝试定义一个在某个位置拆分列表的过程。
(define split-helper
(lambda (lst i lst2)
(cond
((= i 0) (cons lst2 lst))
(else split-helper (rest lst) (- i 1) (first lst)))))
(define split
(lambda (lst i)
(split-helper lst i '())))
到目前为止,这是我的代码。 一个示例测试用例是:
(split '(a b a c) 0) => '(() (a b a c))
(split '(a b a c) 2) => '((a b) (a c))
我的代码在 i 为 0 时有效,但当它是任何其他数字时,它只返回
'a
我有逻辑错误吗?
你有几个错误:
list
来构建输出,并在最后执行(reverse lst2)
,因为我们将以相反的顺序构建它。lst2
参数中构建一个新列表,您应该向它添加cons
元素。split-helper
,而是忘记用括号将其括起来!这应该可以解决所有问题:
(define split-helper
(lambda (lst i lst2)
(cond
((= i 0) (list (reverse lst2) lst))
(else (split-helper (rest lst) (- i 1) (cons (first lst) lst2))))))
(define split
(lambda (lst i)
(split-helper lst i '())))
它按预期工作:
(split '(a b a c) 0)
=> '(() (a b a c))
(split '(a b a c) 2)
=> '((a b) (a c))
您的split-helper
函数递归应该输出(cons (first lst) lst2)
not (first lst)
和'(list lst2 lst)
not (cons lst2 lst)
#lang racket
(define (split lst i)
(cond
[(> 0 i) "i must greater or equal to zero"]
[(< (length lst) i) "i too big"]
[(= (length lst) i) (list lst '())] ; you can remove this line
[else
(local
[(define (split-helper lst i lst2)
(cond
[(zero? i)
(list lst2 lst)]
[else
(split-helper (rest lst) (- i 1) (cons (first lst) lst2))]))]
(split-helper lst i '()))]))
;;; TEST
(map (λ (i) (split '(1 2 3 4 5) i)) (build-list 10 (λ (n) (- n 2))))
尝试这个:
(define split
(lambda (l pos)
((lambda (s) (s s l pos list))
(lambda (s l i col)
(if (or (null? l) (zero? i))
(col '() l)
(s s (cdr l) (- i 1)
(lambda (a d)
(col (cons (car l) a) d))))))))
(split '(a b c d e f) 2)
(split '(a b c d e f) 0)
(split '(a b c d e f) 20)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.