简体   繁体   中英

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

'a

Do I have a logic error?

You have a couple of errors:

  • In the base case, you should use list to build the output, and do a (reverse lst2) at the end, because we'll build it in the opposite order.
  • You're not building a new list in the lst2 parameter, you're supposed to cons elements to it.
  • You're not actually calling 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))

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))))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM