最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin7浏览0评论

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.

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.

Share Improve this question edited Mar 11 at 21:54 primfaktor asked Mar 10 at 16:11 primfaktorprimfaktor 2,99928 silver badges35 bronze badges 1
  • It seems that Racket does not support named groups. See docs.racket-lang./guide/An_Extended_Example.html – Bohemian Commented Mar 10 at 23:00
Add a comment  | 

1 Answer 1

Reset to default 2

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.

发布评论

评论列表(0)

  1. 暂无评论