Skip to content

Instantly share code, notes, and snippets.

@kmicinski
Created February 17, 2026 21:13
Show Gist options
  • Select an option

  • Save kmicinski/905aa47321fea4be43233155da855baf to your computer and use it in GitHub Desktop.

Select an option

Save kmicinski/905aa47321fea4be43233155da855baf to your computer and use it in GitHub Desktop.
CIS352 'S26
#lang racket
;; CIS352 -- Practice on Pattern Matching
;;
;; If you want more practice, I have a video here: https://www.youtube.com/watch?v=RJFkmh9Wo8o
(define (filter f l)
(if (empty? l)
'()
(cons (f (first l)) (filter f (rest l)))))
(define (filter-m f l)
(match l
['() '()] ;; we know l = '()
[`(,hd ,tl ...)
(cons (f hd) (filter f tl))])) ;; we l = (cons hd tl)
;;(every-other '()) => '()
;;(every-other '(1)) => '(1)
;;(every-other '(1 2)) => '(1)
;;(every-other '(1 2 3)) => '(1 3)
(define (every-other l)
(cond [(empty? l) '()]
[(equal? (length l) 1) l]
[else (cons (first l) (every-other (rest (rest l))))]))
(every-other-m '(1 2 3 4 5))
(define (every-other-m l)
(match l
['() '()]
[`(,hd) l]
[`(,fst ,snd ,rst ...) ;; fst = 1, snd = 2 rest = '(3 4 5)
(cons fst (every-other-m rst))]))
;;(every-other-m '(1 2 3 4 5))
;;= (match '(1 2 3 4 5)
;; ['() '()]
;; [`(,hd) l]
;; [`(,fst ,_ ,rst ...) ;; fst = 1, snd = 2 rest = '(3 4 5)
;; (cons fst (every-other-m rst))])
;; = (cons 1 (every-other-m '(3 4 5)))
;; = (cons 1 (cons 3 (every-other-m '(5))))
;; = (cons 1 (cons 3 '(5))) = '(1 3 5)
;; (every-other-m '(1 2 3 4 5 6))
;; = (cons 1 (every-other-m '(3 4 5 6)))
;; = (cons 1 (cons 3 (every-other-m '(5 6))))
;; = (cons 1 (cons 3 (cons 5 (every-other-m '()))))
;; = (cons 1 (cons 3 (cons 5 '())))
;; Translate the following to use match
(define (count-1s l)
(cond [(empty? l) 0]
[(equal? (first l) 1) (+ 1 (count-1s (rest l)))]
[else (count-1s (rest l))]))
(define (count-1s-m l)
(match l
['() 'todo]
[`(1 ,tl ...) 'todo]
[`(,x ,tl ...) 'todo]))
(define (map f l)
(if (empty? l)
'()
(cons (f (first l)) (rest l))))
(define (map-m f l)
(match l
['() 'todo]
[`(,fst ,rst ...) 'todo]))
;; Translate from using match to using if / empty? / etc...
(define (foo l)
(match l
['() 5]
[`(1 ,rst ...) (+ 1 (foo rst))]
[`(,x ,rst ...) (+ 2 (foo rst))]))
(define (foo-using-cond l)
(cond [(equal? l '()) 5]
[(equal? (first l) 1) (+ 1 (foo-using-cond (rest l)))]
[else (+ 2 (foo-using-cond (rest l)))]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment