Racket,将列表拆分为两个不同大小的列表

时间:2017-04-13 16:17:02

标签: racket

此代码将列表拆分为两个相同大小的列表:

(define (split ls)
  (if (or (null? ls) (null? (cdr ls)))
      (list ls '())
      (let ((next (split (cddr ls))))
        (list (cons (car ls) (car next))
              (cons (cadr ls) (cadr next))))))

我想构建一个代码(define(split size ls)),其中size有一个值,例如:0.20,0.50,0.63,它是将转到第一个列表的数字(以%为单位)。 / p>

1 个答案:

答案 0 :(得分:0)

这是一种方法。

可以使用您的函数split-at而不是使用辅助函数split

#lang racket

; clamp : number number -> number
;   make sure x is in the interval [a;b],
;   if not return a or b.
(define (clamp x a b)
  (max (min x b) a))


; split-list : number list -> list list
;   return two values:
;     - appending the two lists will produce the a list equal to the input list xs
(define (split-list pct xs)
  ; find the position to split the list
  (define pos (exact-round (* (clamp pct 0.0 1.0) (length xs))))
  ; split it
  (split-at xs pos))

(split-list 0.00 '(a b c d))
(split-list 0.25 '(a b c d))
(split-list 0.50 '(a b c d))
(split-list 0.75 '(a b c d))
(split-list 1.00 '(a b c d))