Created
February 18, 2014 00:41
-
-
Save gatlin/9062283 to your computer and use it in GitHub Desktop.
Playing with ADTs and other bullshit
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 racket | |
; simple cons pairs | |
(define (my-cons fst snd) | |
(λ (f) (f fst snd))) | |
(define (my-first c) | |
(c (λ (a b) a))) | |
(define (my-second c) | |
(c (λ (a b) b))) | |
(define a (my-cons 1 2)) | |
(my-first a) | |
(my-second a) | |
; algebraic data types | |
(define Nil (λ () (λ (x1 x2) (x1)))) | |
(define Cons (λ (head tail) (λ (x1 x2) (x2 head tail)))) | |
(define (list-length xs) | |
(xs (λ () 0) | |
(λ (_ tail) | |
(1 . + . (list-length tail))))) | |
(define (list-map f xs) | |
(xs (λ () (Nil)) | |
(λ (head tail) | |
(Cons (f head) (list-map f tail))))) | |
(define (list-show xs) | |
(xs (λ () "") | |
(λ (head tail) | |
(string-append (number->string head) (list-show tail))))) | |
(define my-list (Cons 1 (Cons 2 (Nil)))) | |
(list-show | |
(list-map (λ (x) (+ 1 x)) my-list)) | |
; define a "person" | |
(define Human (λ (name age) | |
(λ (a b) (a name age)))) | |
(define Corporation (λ (name age state taxId) | |
(λ (a b) (b name age state taxId)))) | |
(define (birthday ps) | |
(ps (λ (name age) (Human name (+ 1 age))) | |
(λ (name age state taxId) | |
(Corporation name (+ 1 age) state taxId)))) | |
(define (show-person ps) | |
(define space " ") | |
(ps (λ (name age) (string-append name space (number->string age))) | |
(λ (name age state taxId) | |
(string-append name | |
space | |
(number->string age) | |
space | |
state | |
space | |
taxId)))) | |
(define gatlin (Human "gatlin" 25)) | |
(define richard (Human "richard" 31)) | |
(define megacorp (Corporation "megacorp" 100 "TX" "123456789")) | |
(show-person (birthday gatlin)) | |
(show-person (birthday richard)) | |
(show-person (birthday megacorp)) | |
; something more interesting | |
(define Nothing (λ () (λ (a b) (a)))) | |
(define Just (λ (x) (λ (a b) (b x)))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment