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

Let's say I have this part of a pattern match:(definematch (make lst)[((list)) (const #f '(

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744835561a4596240.html

相关推荐

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

    Let's say I have this part of a pattern match:(definematch (make lst)[((list)) (const #f '(

    2天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信