Reputation: 39
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
'a
Do I have a logic error?
Upvotes: 1
Views: 133
Reputation: 702
Your split-helper
function recursion should output (cons (first lst) lst2)
not (first lst)
and '(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))))
Upvotes: 1
Reputation: 235994
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.lst2
parameter, you're supposed to cons
elements to it.split-helper
, you forgot to surround it with brackets!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))
Upvotes: 3
Reputation: 15793
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)
Upvotes: 0