pattern-matchingracket

Can I name part of a pattern in Racket's match?


Let's say I have this part of a pattern match:

(define/match (make lst)
  [((list)) (const #f '())]
  [((list (cons _ n))) (cons (make-tree-node n) '())]
  [((list-rest (cons parent pnum) (cons child cnum) rest))
    ; do stuff that uses the child/cnum pair without having to re-cons it
    ; also might want to use the rest of the list without having to (rest lst)
   ])

In F# among others, I can name parts of a pattern to use them in the corresponding match expression. I'm looking for a similar thing in Racket but can't find anything.

Whether stuff is clearer with a named pattern depends on the context. But certainly it wouldn't be re-executing destructuring code that the match macro already had to do anyway.


Solution

  • Yes, by using and to both match a destructured construct and the entire thing:

    (define/match (make lst)
      [((list)) (const #f '())]
      [((list (cons _ n))) (cons (make-tree-node n) '())]
      [((list-rest (and (cons parent pnum) p) (and (cons child cnum) c) rest))
       ;; can use parent, pnum, p, etc. here.
       ])
    

    Side note: From the names, it looks like you're using lists to represent some sort of tree. Consider using structures instead, for more efficient access to fields and less memory use.