@notjack hm. did you try that? or maybe i’m doing something wrong? engine.rkt> (match '(x) [(or (list) (list v)) v])
; stdin::461: match: variable not bound in all or patterns
; at: v
; in: (or (list) (list v))
@jjwiseman I didn’t, I skimmed the match grammar and took a shot in the dark :)
@jjwiseman I got this to work, but it’s pretty unpleasant to read:
> (define (f lst)
(match lst
[(or (and (list) (app (const #f) v)) (list v)) v]))
> (f '(x))
'x
> (f '())
#f
> (f '(x y))
match: no matching clause for '(x y)
Yes, (or pattern-that-binds-id (app (const #f) id))
is the only “trick” I know for that. [Note that if #f
could be a valid value for id
, you could use some symbol like 'not-found
or singleton struct
or whatever to mean “didn’t match anything to bind to id
”.] I’ve thought about defining a match-expander for this to reduce the tedium… But in my own experience the need for zero-or-one is usually just a detail of some bigger pattern I need to address with a separate match clause, anyway.
Like, if in the match handler for that clause, I need a sub-test whether id
was bound to a non-#f
value? Then I probably just need a separate match clause altogether.
At least, that’s been my experience. Yours may vary. @notjack @jjwiseman
i was looking for a way to match something that looked like keyword arguments. it felt like it should have been relatively simple, i was surprised that match
didn’t support it directly.
I’m not sure what you mean by something that looks like keyword arguments. There is a hash-table
pattern.
FWIW, syntax-parse
can match raw datums (non-syntax objects) and is very good at parsing keyword arguments. :)
If you mean literally keyword args, then maybe you mean a macro and want syntax-parse
instead?
jinx
:)
e.g i would like to match (rule #:lhs (foo) #:rhs (bar))
or something like that, where lhs and rhs can appear in any order and are optional.
oh, syntax-parse
. i didn’t realize it could handle datums (data?)
thanks, everyone!
I think syntax-parse
will wrap values in syntax objects even if you feed it non-syntax, though, which might not be what you want.