public
Created

Re-implementing basic list functionality using functions as the storage mechanism.

  • Download Gist
functional-list.rkt
Racket
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#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))))))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.