Skip to content

Instantly share code, notes, and snippets.

@gbluma
Created September 29, 2013 13:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbluma/6752652 to your computer and use it in GitHub Desktop.
Save gbluma/6752652 to your computer and use it in GitHub Desktop.
Exhaustive pattern matching (refinement types!) in Typed/Racket.
#lang typed/racket
;; We get exhaustive pattern matching
(: f ((U String Integer) -> Boolean))
(define (f x)
(cond
[(string? x) (string=? x "hi")] ; covers string needs
[(exact-nonnegative-integer? x) (= x 7)] ; covers positive integers
[(even? x) (= x -8)] ; we can actually cover a subset of negative integers
[(integer? x) (= x -9)])) ; needed to cover rest of negative integers
;; We can recreate the Maybe type in racket
(struct: None ())
(struct: (a) Just ([v : a]))
(define-type (Maybe a) (U None (Just a)))
;; we can use the maybe type in functions
(: find (Number (Listof Number) -> (Maybe Number)))
(define (find v l)
(cond [(null? l) (None)]
[(= v (car l)) (Just v)]
[else (find v (cdr l))]))
;; and even exhaustively pattern match using cond
(: tell ((Maybe Number) -> Number))
(define (tell a)
(cond
[(Just? a) (Just-v a)]
[(None? a) 0]))
(print (tell (Just 3)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment