monica
monica

Reputation: 1065

How to match a struct

I want to match a struct test, and build a struct from that, but how can I do that?
I can't even use eval to do this?

Please reference to the code,

#lang racket

  (struct test (num) #:prefab)

  (define s `((AK= #(struct:test 100))
   (AV)
   ))

  (define ns (make-base-namespace))
   (define (set-state-space-vals!)
   (namespace-set-variable-value! 'test test #f ns)
   )

(match s
   [`((AK= #(struct:test ,val) (AV)))  ;; can't match
     (displayln val)
    ]
   [`((AK= ,val) (AV))   ;; can match, but how to build the struct?
     (struct? (eval val ns))
     (match-define (struct test (num)) (eval val ns)) ;this will fail
     (displayln num)
    ]  )

Upvotes: 1

Views: 335

Answers (2)

J. Ian Johnson
J. Ian Johnson

Reputation: 309

Also, though it's not in the documentation for match, `((AK= #s(test ,val)) (AV)) is a valid pattern.

Upvotes: 1

Asumu Takikawa
Asumu Takikawa

Reputation: 8523

I think you were looking for something like this:

(struct test (num) #:prefab)

(define s '((AK= #s(test 100)) (AV)))

(match s
  [`((AK= ,(struct test (val))) (AV))
   (displayln val)])

Also, in general using eval in a situation like this is highly inadvisable. When in doubt, do not use eval. See this blog post for a longer explanation. You might also want to see the Guide entries on prefabs and pattern matching.

Upvotes: 3

Related Questions