How to split a list into two parts in Scheme

笑着哭i 提交于 2019-12-11 03:04:07

问题


Example: (split '(1 2 3 4) '3)

the Answer should be: ((1 2 3) 4)

The function required 1 list and 1 number, the output should be nested list the nested list consist of all elements of "mylist" which are equal or less than the "num", and the greater number should be on the right of the list.

I tried but out put is only one list:

(define (split mylist num)
  (cond
    ((null? mylist)'())
    ((list? (car mylist))(split(car mylist) num))
    ((> (car mylist) num)(split(cdr mylist) num))
    (else(cons (car mylist) (split(cdr mylist) num)))))

回答1:


Here's one possible solution, using built-in procedures in Racket:

(define (split mylist num)
  (cons
   (takef mylist (lambda (n) (<= n num)))
   (dropf mylist (lambda (n) (<= n num)))))

For example:

(split '(1 2 3 4) 3)
=> '((1 2 3) 4)

(split '(1 2 3 4 5) 3)
=> '((1 2 3) 4 5)



回答2:


A simple solution:

(define (split-list xs y) 
  (define (less x)    (<= x y))
  (define (greater x) (>  x y))
  (list (filter less xs)
        (filter greater xs)))

An alternative:

(define (split-list xs y) 
  (define (less x) (<= x y))
  (define-values (as bs) (partition less xs))
  (list as bs))

(split-list '(1 2 3 4) 3)



回答3:


This is roll your own version using named let. It makes one pass through the data and the result is in reverse order since it's the most effective.

(define (binary-bucket-sort lst threshold)
  (let loop ((lst lst) (less-equal '()) (greater '()))    
    (cond ((null? lst) 
           (cons less-equal greater))
          ((<= (car lst) threshold) 
           (loop (cdr lst) (cons (car lst) less-equal) greater))
          (else 
           (loop (cdr lst) less-equal (cons (car lst) greater))))))

(binary-bucket-sort '(1 5 9 2 6 10 3 7 9 8 4 0) 5) 
; ==> ((0 4 3 2 5 1) . (8 9 7 10 6 9))



回答4:


If you're comfortable with some of the more functional constructs in Racket, such as curry and the like, you can use this rather compact approach:

(define (split-list xs y) 
  (call-with-values (thunk (partition (curry >= y) xs)) cons))

> (split-list '(1 2 3 4 5 6 7) 3)
'((1 2 3) 4 5 6 7)


来源:https://stackoverflow.com/questions/30003395/how-to-split-a-list-into-two-parts-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!