如何将方案中的列表拆分成n个大小相等的块?

人气:1,003 发布:2022-10-16 标签: lisp scheme racket

问题描述

我在试拍中的一些练习题,被困在这道题上了

我要做的是定义一个列表,如(Partition‘(1 2 3 4 5 6)3),然后调用Return’((1 2)(3 4)(3 4))。(三个大小相等的分区)

例如,(Partition‘(1 2 3 4)3)将提供输出 (1)(2)(3 4) 其中n为3是要创建的分区数

下面我试过解决这个问题

(define (threesize n xs)
  (let loop ([grouped '()] [xs xs] [l (length xs])
    (cond
      [(empty? xs)
       (reverse grouped)]
      [(<= l n)
       (loop (cons xs grouped) '() 0)]
      [else (let-values ([(taken dropped) (split-at xs n)])
              (loop (cons taken grouped)
                    dropped
                    (- l n)))])))
总的来说,我对编程和球拍非常陌生,所以请原谅我在这方面的技能。谢谢您

推荐答案

对于那些编程和游戏新手来说,看看问题是如何解决的可能很有趣 这样的问题可以使用 Htdf(How to Design Functions) 在Drracket中使用BSL(初学者语言)的设计方法。

从存根开始,包含签名和目的,以及最小检查-预期

319