donkey
donkey

Reputation: 1448

Pattern matching in Racket

I have this code snippet in Haskell:

matchEx :: Expr -> [Expr]
matchEx (Number n) = undefined
matchEx (Boolean b) = undefined
matchEx (If condStatement thenStatement elseStatement) = undefined

What would the equivalent pattern matching looks like in racket? After looking at the documentation, this is what I have. Thanks.

(define (matchEx-calls expr)
  (match expr
    [(literal n) ([])]
    [(id ident) ([])]
    [(If condStatement thenStatement elseStatement) ([])] 
   )
  )

Upvotes: 2

Views: 2197

Answers (1)

soegaard
soegaard

Reputation: 31147

Here is an example to get you started:

#lang racket

(struct Expr ()              #:transparent)
(struct Number  Expr (n)     #:transparent)
(struct Boolean Expr (b)     #:transparent)
(struct Or      Expr (exprs) #:transparent)

(define (format-Expr e)
  (define ~ format-Expr)
  (match e
    [(Number n)  (~a n)]
    [(Boolean b) (if b "true" "false")]
    [(Or es)     (match es
                   ['()              "true"]
                   [(list e)         (~ e)]
                   [(list e1 e2)     (~a (~ e1) " or " (~ e2))]
                   [(list e1 es ...) (~a (~ e1) " or " (~ (Or es)))])]
    [(? Expr? e)
     ; we get here if we forgot to implement a case
     (error 'format-expr (~a "internal error, got: " e))]
    [_
     ; this on the other hand is an user error
     (error 'format-expr (~a "expected an Expr, got: " e))]))

(format-Expr (Or (list (Boolean #t) (Boolean #f))))

Upvotes: 2

Related Questions