I was in need of applying a function to a list of values that contains sub-lists. map
can not works on nested lists and i can not find a procedure in the scheme library or SRFI so i wrote my own :
(module map-nested racket/base
(provide map-nested )
;; (map-nested sin '(0.1 0.2 (0.3) 0.4))
;; '(0.09983341664682815 0.19866933079506122 (0.29552020666133955) 0.3894183423086505)
(define (map-nested f L)
(define (map-nested-aux x)
(if (list? x)
(map map-nested-aux x)
(apply f (list x))))
(map map-nested-aux L))
)
Check Shawn's collection of tree functions.
2 Likes
yes map-tree or walk-tree should make it, map-tree i suppose, but haven't test it as my solution is already good.
shawnw
June 2, 2025, 10:09pm
4
leaf-map
in particular:
> (require soup-lib/tree)
> (leaf-map sin '(0.1 0.2 (0.3) 0.4))
'(0.09983341664682815
0.19866933079506122
(0.29552020666133955)
0.3894183423086505)
1 Like
oh yes ,it is true it is exactly and only the leaf (leaves ?) i'm aiming.
FWIW, Instead of (apply f (list x))
, (f x)
should work and be more performant (since the argument list is fixed, we don't need the indirection of apply
).
1 Like
yes, i corrected the code (i do not know why i overcomplexified my code,sometimes things are so simple, we do not see them )
and another people outside Racket discourse provide me with this more concise solution:
(define (map-nested f L)
(if (list? L)
(map (lambda (x) (map-nested f x))
L)
(f L)))