list - 在 Racket 中将列表拆分为 posn
问题描述
我有这个函数,它接受一个列表和一个数字,它将列表拆分到第 n 个元素并使其成为 posn,例如:
(split (list 1 2 3 4) 2) = (make-posn (list 1 2) (list 3 4))
(split (list 1 2 3 4) 0) = (make-posn empty (list 1 2 3 4))
(split (list empty 23) = (make-posn empty empty)
(split (list 1 2 3 4) 1) = (make-posn (list 1) (list 2 3 4))
关键是,我有一个辅助功能来制作第一部分
(define (aux l n)
(cond[(empty? l) empty]
[(zero? n) empty]
[(positive? n) (cons (first l)(aux (rest l)(sub1 n)))]))
(aux (list 1 2 3 4) 2)) = (list 1 2)
但我不知道如何制作第二部分
解决方案
你肯定走上了正轨!您可以进行第二个aux2
循环以类似方式构建输出的第二部分 -
(define (split l n)
;; left portion (your code)
(define (aux1 l n)
(cond
[(empty? l) empty]
[(zero? n) empty]
[(positive? n)
(cons (first l)
(aux1 (rest l)
(sub1 n)))]))
;; right portion (new code)
(define (aux2 l n)
(cond
[(empty? l) empty]
[(zero? n) l]
[(positive? n)
(aux2 (cdr l)
(sub1 n))]))
;; combine
(posn (aux1 l n) (aux2 l n)))
上面我们使用posn
的是根据您问题中的数据结构建模的 -
(struct posn (l r) #:transparent )
你用split
另一种方式写作。aux1
我们可以同时折叠aux2
成一个单一的aux
——
(define (split ls n)
(define (aux n l r)
(cond
[(or (empty? r) (zero? n))
(posn (reverse l) r)]
[(positive? n)
(aux (sub1 n)
(cons (car r) l)
(cdr r))]
[else
(error 'split "cannot split using a negative number")]))
(aux n empty ls))
aux
或者我们可以使用 continuation-passing 风格编写-
(define (split t n)
(define (aux t n return)
(cond
[(or (empty? t) (zero? n))
(return empty t)]
[(positive? n)
(aux (cdr t)
(sub1 n)
(lambda (l r)
(return (cons (car t) l) r)))]
[else
(error 'split "cannot split using a negative number")]))
(aux t n posn))
使用您问题中的示例-
(split (list 1 2 3 4) 2)
(split (list 1 2 3 4) 0)
(split empty 23)
(split (list 1 2 3 4) 1)
上面的每个实现都会split
产生相同的输出 -
(posn '(1 2) '(3 4))
(posn '() '(1 2 3 4))
(posn '() '())
(posn '(1) '(2 3 4))
推荐阅读
- sed - sed 对一系列行加上单行进行操作
- c# - c# Linq 按嵌套列表的成员对列表进行排序
- java - springboot可执行jar中的JNI NoClassDefFoundError
- javascript - 嗨,我在添加后删除输入标签时遇到问题。问题是当我单击删除按钮时输入标签
- swift - 如何在 Swift 中比较类型?
- python - 如何缩放 3D 和 2D 子图以使相应的轴具有相同的长度?
- mongodb - 如何使用 Mongoose 将具有 ID 数组的嵌套字段填充到另一个集合?
- uml - 对于作为同一流程的一部分进行推送和拉取的流程,正确的 FLOWCHART 表示法是什么?
- python - ERROR selenium.common.exceptions.StaleElementReferenceException(他的浏览器弹出窗口没有关闭)
- kubernetes - 通过 Kubernetes 中的多个内部地址访问服务