How to use append-map in Racket (Scheme)

I don’t quite understand what the append-map command does in racket, and I don’t understand how to use it, and it’s hard for me to find documentation suitable for it that is easy to understand. Can anyone demonstrate what the team is doing and how it works?

+4
source share
2 answers

The append-map procedure is useful for creating one list from a list of subscribers after applying the procedure for each sublist. In other words, this code:

 (append-map proc lst) 

... semantically equivalent to this:

 (apply append (map proc lst)) 

... Or that:

 (append* (map proc lst)) 

The idiom apply-app-to-a-list-of-sublists is sometimes called flattening a list of subscriptions. Let's look at some examples, this right here in the documentation:

 (append-map vector->list '(#(1) #(2 3) #(4))) '(1 2 3 4) 

For a more interesting example, check out this code from Rosetta Code to find all permutations of the list:

 (define (insert lne) (if (= 0 n) (cons el) (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 pn (car l))) (seq 0 (length p)))) (permute (cdr l)))))) 

The latter procedure can be expressed more concisely using the append-map :

 (define (permute l) (if (null? l) '(()) (append-map (lambda (p) (map (lambda (n) (insert pn (car l))) (seq 0 (length p)))) (permute (cdr l))))) 

In any case, the result will be as expected:

 (permute '(1 2 3)) => '((1 2 3) (2 1 3) (2 3 1) (1 3 2) (3 1 2) (3 2 1)) 
+9
source

In Common Lisp, the function is called "mapcan", and it is sometimes used to combine filtering with display:

 * (mapcan (lambda (n) (if (oddp n) (list (* nn)) '())) '(0 1 2 3 4 5 6 7)) (1 9 25 49) 

In Racket, which will be:

 > (append-map (lambda (n) (if (odd? n) (list (* nn)) '())) (range 8)) '(1 9 25 49) 

But it’s better to do this:

 > (filter-map (lambda (n) (and (odd? n) (* nn))) (range 8)) '(1 9 25 49) 
+3
source

All Articles