Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Re-implementing basic list functionality using functions as the storage mechanism.
#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)
(+ 1 (length (rest l))))))
; Reverse a list
(define reverse
(λ (l)
(let loop ([l l] [acc empty])
(if (empty? l)
(loop (rest l)
(pair (first l) acc))))))
; Append two lists
(define append
(λ (l r)
(if (empty? l)
(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
You can’t perform that action at this time.