resyntax icon indicating copy to clipboard operation
resyntax copied to clipboard

Suggest `match` with `regexp` instead of `regexp-match`

Open jackfirth opened this issue 7 months ago • 1 comments

In this code, the use of cond and regexp-match can be expressed more cleanly using match with the regexp pattern. This probably shouldn't be rewritten unless 1) every non-else branch of the cond is using the lambda-based form and 2) all of the match patterns use define to name the extracted groups, if there are multiple groups. So this test case ought to pass:

#lang resyntax/test
require: resyntax/default-recommendations default-recommendations
header:
- #lang racket

test: "original code should be refactorable to new code"
--------------------
(define re #rx"^[ \t\n]*([0-9]+)[ \t\n]*,(.*)$")
(define (f str)
  (cond
    [(regexp-match re str)
     =>
     (lambda (m)
       (define a (cadr m))
       (define b (caddr m))
       (list a b))]
    [else 'else]))
====================
(define re #rx"^[ \t\n]*([0-9]+)[ \t\n]*,(.*)$")
(define (f str)
  (match str
    [(regexp re (list _ a b)) (list a b)]
    [else 'else]))
--------------------

There are some similar cases in DrRacket's codebase but refactoring all of them is questionable. The cases where there's multiple capture groups and none of them have named variables associated with them ought to be left alone.

jackfirth avatar Jul 30 '25 02:07 jackfirth