如何在球拍中使用附加贴图(方案) [英] How to use append-map in Racket (Scheme)
问题描述
我不完全了解append-map命令在球拍中的作用,也不了解如何使用它,而且我很难在网上找到一些可以理解的文档.有人可以演示该命令的确切功能以及其工作原理吗?
I don't fully understand what the append-map command does in racket, nor do I understand how to use it and I'm having a pretty hard time finding some decently understandable documentation online for it. Could someone possibly demonstrate what exactly the command does and how it works?
推荐答案
在将过程应用于每个子列表之后,append-map
过程对于在子列表列表中创建单个列表很有用.换句话说,这段代码:
The append-map
procedure is useful for creating a single list out of a list of sublists after applying a procedure to each sublist. In other words, this code:
(append-map proc lst)
...在语义上与此等效:
... Is semantically equivalent to this:
(apply append (map proc lst))
...或者这个:
(append* (map proc lst))
将子列表应用于列表的习惯用法有时称为 flatting 子列表列表.让我们看一些示例,这个示例是正确的
The applying-append-to-a-list-of-sublists idiom is sometimes known as flattening a list of sublists. Let's look at some examples, this one is right here in the documentation:
(append-map vector->list '(#(1) #(2 3) #(4)))
'(1 2 3 4)
对于更有趣的示例,请看一下Rosetta Code中的代码,以查找所有列表的排列:
For a more interesting example, take a look at this code from Rosetta Code for finding all permutations of a list:
(define (insert l n e)
(if (= 0 n)
(cons e l)
(cons (car l)
(insert (cdr l) (- n 1) e))))
(define (seq start end)
(if (= start end)
(list end)
(cons start (seq (+ start 1) end))))
(define (permute l)
(if (null? l)
'(())
(apply append (map (lambda (p)
(map (lambda (n)
(insert p n (car l)))
(seq 0 (length p))))
(permute (cdr l))))))
使用append-map
可以更简洁地表达最后一个过程:
The last procedure can be expressed more concisely by using append-map
:
(define (permute l)
(if (null? l)
'(())
(append-map (lambda (p)
(map (lambda (n)
(insert p n (car l)))
(seq 0 (length p))))
(permute (cdr l)))))
无论哪种方式,结果都符合预期:
Either way, the result is as expected:
(permute '(1 2 3))
=> '((1 2 3) (2 1 3) (2 3 1) (1 3 2) (3 1 2) (3 2 1))
这篇关于如何在球拍中使用附加贴图(方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!