Created
October 9, 2013 05:03
-
-
Save jpverkamp/6896457 to your computer and use it in GitHub Desktop.
Re-implementing basic list functionality using functions as the storage mechanism.
This file contains hidden or 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 | |
| ; Empty list | |
| (define empty (λ (l) (l 'error 'error #t))) | |
| (define empty? (λ (l) (l (λ (a d e) e)))) | |
| ; Build and take apart lists | |
| (define pair (λ (a d) (λ (l) (l a d #f)))) | |
| (define first (λ (l) (l (λ (a d e) a)))) | |
| (define rest (λ (l) (l (λ (a d e) d)))) | |
| ; Get the nth item of a list | |
| (define nth | |
| (λ (l i) | |
| (if (zero? i) | |
| (first l) | |
| (nth (rest l) (- i 1))))) | |
| ; Calculate the length of a list | |
| (define length | |
| (λ (l) | |
| (if (empty? l) | |
| 0 | |
| (+ 1 (length (rest l)))))) | |
| ; Reverse a list | |
| (define reverse | |
| (λ (l) | |
| (let loop ([l l] [acc empty]) | |
| (if (empty? l) | |
| acc | |
| (loop (rest l) | |
| (pair (first l) acc)))))) | |
| ; Append two lists | |
| (define append | |
| (λ (l r) | |
| (if (empty? l) | |
| r | |
| (pair (first l) (append (rest l) r))))) | |
| ; Helpers to convert with traditional lists | |
| (define list->flist | |
| (λ (l) | |
| (foldl pair empty l))) | |
| (define flist->list | |
| (λ (l) | |
| (if (empty? l) | |
| '() | |
| (cons (first l) (flist->list (rest l)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment