jackfirth / resyntax

A Racket refactoring engine
Apache License 2.0
51 stars 10 forks source link

(apply + (map ...)) -> for/sum #231

Open sorawee opened 8 months ago

sorawee commented 8 months ago

E.g.

(apply + (map length '((1) (2 3))))

is equivalent to

(for/sum ([x (in-list '((1) (2 3)))])
  (length x))

More generally:

(apply + (map f xs))

is equivalent to

(for/sum ([x (in-list xs)])
  (f x))

But the latter doesn't create an intermediate data structure, so it's better.

Probably can do the same with filter.

jackfirth commented 7 months ago

This rule already exists, but it doesn't fire when the function given to map isn't a lambda because there isn't a good candidate for a variable name to pick automatically. The fusion seems valuable enough that it might be worth doing it anyway in that case and just using v as the variable for everything.