0

In racket I made this basic piece of code. However racket doesn't seem to like the first clause - trying to run this, I get the error "match: syntax error in pattern in: (- 3 9)"

(define/match (prob i)
    [((- 3 9)) 0]
    [(_) 4]
)

The weird thing is that if instead of the subtraction procedure, I used the "list" procedure (i.e. ((list 3 9)) instead of ((- 3 9)) ), the code works. What gives?

CSSTUDENT
  • 103
  • 2

1 Answers1

1

If your goal is to check whether the argument i is equal to the value that (- 3 9) resolves to, then the issue is that Racket match forms do not accept arbitrary expressions as patterns. For more information on what kind of patterns can be used with match forms, check out the Racket documentation on Pattern Matching (you may notice that (list ...) is included among the allowed patterns, as you observed!). However the simple answer (as Alex Knauth commented) is to replace (- 3 9) with (== (- 3 9)).

On the other hand, if your goal is to check whether the argument supplied to (prob i) is literally the expression (- 3 9), regardless of what that might evaluate to, then define/match will not suffice. Racket functions are pass by value. So when someone passes an expression as the argument i to your prob function, i is equal to the evaluated result of that expression, viz

(define (some-function some-argument)
    some-argument) ; we just get the number 3 for some-argument
                   ; and have no way of knowing via this function
                   ; that someone actually passed us the expression
                   ; (- (- 9 1) 5)

(some-function (- (- 9 1) 5))

We would have to use a different tool, called a macro. Macros operate on the text of the program before symbols are evaluated. A macro implementation of your (prob i) function would work like this on the REPL:

> (define-syntax-rule (prob i)
    (if (equal? 'i '(- 3 9))
      0
      4))
> (prob (- 3 9))
0
> (prob -6)
4
> (prob 78)
4

That is called a "syntax rule". It quotes out the argument i, then compares it to the quoted expression (- 3 9) to see if that was supplied as i. Let me know if you're still having any issues! Good luck!

Alex V
  • 3,416
  • 2
  • 33
  • 52