[英]Spliting a list at a certain location using Racket/Scheme
I'm trying to define a procedure that splits a list at a certain location.我正在尝试定义一个在某个位置拆分列表的过程。
(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 '())))
This is my code so far.到目前为止,这是我的代码。 An example test case is:
一个示例测试用例是:
(split '(a b a c) 0) => '(() (a b a c))
(split '(a b a c) 2) => '((a b) (a c))
My code works when i is 0 but when it's any other number it just returns我的代码在 i 为 0 时有效,但当它是任何其他数字时,它只返回
'a
Do I have a logic error?我有逻辑错误吗?
You have a couple of errors:你有几个错误:
list
to build the output, and do a (reverse lst2)
at the end, because we'll build it in the opposite order.list
来构建输出,并在最后执行(reverse lst2)
,因为我们将以相反的顺序构建它。lst2
parameter, you're supposed to cons
elements to it.lst2
参数中构建一个新列表,您应该向它添加cons
元素。split-helper
, you forgot to surround it with brackets!split-helper
,而是忘记用括号将其括起来! This should fix all the issues:这应该可以解决所有问题:
(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 '())))
It works as expected:它按预期工作:
(split '(a b a c) 0)
=> '(() (a b a c))
(split '(a b a c) 2)
=> '((a b) (a c))
Your split-helper
function recursion should output (cons (first lst) lst2)
not (first lst)
and '(list lst2 lst)
not (cons lst2 lst)
您的
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))))
Try this:尝试这个:
(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.