Created
September 29, 2013 13:45
-
-
Save gbluma/6752652 to your computer and use it in GitHub Desktop.
Exhaustive pattern matching (refinement types!) in Typed/Racket.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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