【问题标题】:Partitioning a list on Scheme对 Scheme 列表进行分区
【发布时间】:2013-03-04 08:54:30
【问题描述】:

我将如何制作一个分区函数,该函数将采用一个数字和一个列表将列表划分为较小的列表列表,其大小由数字给出 这样

Partition 3 '(a b c d e f g h) -> '((a b c) (d e f) (g h)) and etc. using take and drop?

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    我会给你一些提示,以便你自己找到答案。填空:

    (define (partition n lst)
      (cond (<???>                      ; if the list is empty
             <???>)                     ; then return the empty list
            ((< <???> n)                ; if the lists' length is less than n
             <???>)                     ; return a list with lst as its only element
            (else                       ; otherwise
             (cons                      ; cons a list with the result of
              (<???> lst n)             ; grabbing the first n elements of lst with
              (<???> n                  ; the result of advancing the recursion and
                     (<???> lst n)))))) ; removing the first n elements of lst
    

    显然,您必须按照问题描述中的要求在解决方案中的某处使用takedrop。像这样测试您的解决方案:

    (partition 3 '(a b c d e f g h))
    => '((a b c) (d e f) (g h))
    
    (partition 3 '(a b c d e f g h i))
    =>'((a b c) (d e f) (g h i))
    

    【讨论】:

    • 非常感谢!我已经填写了它的空白,我得到 (cond ((empty?lst) lst ((
    • @user1869703 请注意,在第二种情况下,您必须返回“以 lst 作为唯一元素的列表”。换句话说,这个:(list lst)
    猜你喜欢
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多