Last active
August 29, 2015 14:14
-
-
Save turanct/e84be7f355e255c2c1b5 to your computer and use it in GitHub Desktop.
List functions in lisp
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
; The list datatype in scheme is awesome... They are actually nested pairs | |
; so they can be manipulated using the three functions used with pairs. | |
; | |
; - cons: create a pair | |
; - car: return the left side of a pair | |
; - cdr: return the right side of a pair | |
; | |
; This is a fantastic abstraction layer, that can be used to create all other | |
; list functions out there. Some examples: | |
(define (my-length l) | |
(if (null? l) | |
0 | |
(+ 1 (my-length (cdr l))))) | |
(define (my-append la lb) | |
(if (null? la) | |
lb | |
(cons (car la) (my-append (cdr la) lb)))) | |
(define (my-reverse l) | |
(if (null? l) | |
l | |
(my-append (my-reverse (cdr l)) (list (car l))))) | |
(define (my-map fn l) | |
(if (null? l) | |
l | |
(cons (fn (car l)) (my-map fn (cdr l))))) | |
(define (my-filter fn l) | |
(if (null? l) | |
l | |
(if (fn (car l)) | |
(cons (car l) (my-filter fn (cdr l))) | |
(my-filter fn (cdr l))))) | |
(define (my-reduce fn l initial) | |
(if (null? l) | |
initial | |
(my-reduce fn (cdr l) (fn initial (car l))))) | |
(define (my-zip la lb) | |
(if (or (null? la) (null? lb)) | |
'() | |
(cons (cons (car la) (car lb)) (my-zip (cdr la) (cdr lb))))) | |
(define (my-list-ref l n) | |
(cond | |
((null? l) (error "Can't find indexes in empty lists")) | |
((> n (my-length l)) (error "List is smaller than given index")) | |
((= 1 n) (car l)) | |
(else (my-list-ref (cdr l) (- n 1))))) | |
(define (my-last l) | |
(cond | |
((null? l) (error "Can't take the last item of an empty list")) | |
((= 1 (my-length l)) (car l)) | |
(else (my-last (cdr l))))) | |
(define (my-contains? l element) | |
(cond | |
((null? l) #f) | |
((= (car l) element) #t) | |
(else (my-contains? (cdr l) element)))) | |
(define (my-unique l) | |
(cond | |
((null? l) l) | |
((my-contains? (cdr l) (car l)) (my-unique (cdr l))) | |
(else (cons (car l) (my-unique (cdr l)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment