如何在Scheme中将列表分成两部分 [英] How to split a list into two parts in Scheme

查看:47
本文介绍了如何在Scheme中将列表分成两部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:(split '(1 2 3 4) '3)

答案应该是:((1 2 3) 4)

函数需要1个列表和1个数字,输出应该是嵌套列表嵌套列表由mylist"中所有等于或小于num"的元素组成,较大的数字应位于列表的右侧.

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

推荐答案

这是一种可能的解决方案,使用 Racket 中的内置程序:

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

例如:

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

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

这篇关于如何在Scheme中将列表分成两部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆