MC logo

Some Examples

  CSc 404 Documentation And Examples

lec123.lsp
; Sum of squares.
(define (sumsqr x y) (+ (* x x) (* y y)))

; Length of a list.
(define (len lis)
    (if (null? lis) 0 (+ 1 (len (cdr lis))))
)

; Append lists.
(define (app lis1 lis2)
    (if (null? lis1) lis2
        (cons (car lis1) (app (cdr lis1) lis2))
    )
)

; Make each list member a list of itself.
(define (addpar lis)
    (if (null? lis) 
        lis
        (cons (cons (car lis) ()) (addpar (cdr lis)))
    )
)

; Reverse the list.
(define (rev lis)
    (if (null? lis)
        lis
        (append (rev (cdr lis)) (cons (car lis) ()))
    )
)

; Flatten a list: Remove all sublist structure to make a flat list
; containing the same items.
(define (flatten lis)
    (cond 
        ((null? lis) lis)
        ((pair? (car lis)) (flatten (append (car lis) (cdr lis))))
        (#t (cons (car lis) (flatten (cdr lis))))
    )
)