Skip to content

New rule: fuse-map-with-for #764

@jackfirth

Description

@jackfirth

Rule summary

A map expression that produces a list which is immediately iterated over by a for* loop can be fused with the for* loop, if the intermediate list isn't used elsewhere. This avoids constructing the intermediate list and is usually more readable. This should only be applied when the map expression is given a short lambda.

Test case

#lang resyntax/test

test: "original code should be refactorable to new code"
--------------------
#lang racket
(define (f xs g h)
  (define ys (map (λ (x) (g x)) xs))
  (for* ([y (in-list ys)]
         [z (in-list (h y))])
    (displayln z)))
====================
#lang racket
(define (f xs g h)
  (for* ([x (in-list xs)]
         [y (in-list (g x))]
         [z (in-list (h y))])
    (displayln z)))
--------------------

No-change test case

#lang resyntax/test

no-change-test: "code not refactorable"
--------------------
#lang racket
(define (f xs g h)
  (define ys (map (λ (x) (g x)) xs))
  (for* ([y (in-list ys)]
         [z (in-list (h y))])
    (displayln z))
  (displayln ys))
--------------------

Additional context

Spotted this here in racket/drracket#783.

Metadata

Metadata

Assignees

No one assigned

    Labels

    autopilot-candidateThe Copilot Agent should attempt this during a scheduled Autopilot runnew lintIssues suggesting new lints or pull requests implementing new lints

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions