20-CS-4003-001 Organization of Programming Languages Fall 2018
Recursion

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures        Code

Procedures: Permutations

 ```;; returns #t iff a is a member of list lst (define contains? (lambda (lst a) (if (null? lst) #f (if (eq? (car lst) a) #t (contains? (cdr lst) a))))) ;; returns lst minus the first occurrence of a, if any (define remove-first (lambda (lst a) (if (null? lst) lst (if (eq? (car lst) a) (cdr lst) (cons (car lst) (remove-first (cdr lst) a)))))) ;; returns #t iff lists x and y are permutations (define perm? (lambda (x y) (if (null? x) (null? y) (if (contains? y (car x)) (perm? (cdr x) (remove-first y (car x))) #f)))) ;; returns #t iff lst elements are in non-decreasing ;; order (define ordered? (lambda (lst) (or (null? lst) (null? (cdr lst)) (and (<= (car lst) (car (cdr lst))) (ordered? (cdr lst)))))) ``` - Examples: ``` prompt> (contains '(3 4 7 1 2 3 4 6 6 2 8) 4) ;Value: #t prompt> (contains '() 1) ;Value: #f prompt> (contains '(1 2 3 4) 'a) ;Value: #f prompt> (remove-first '(3 4 7 1 2 3 4 6 6 2 8) 4) ;Value 11: (3 7 1 2 3 4 6 6 2 8) prompt> (remove-first '() 1) ;Value: () prompt> (remove-first '(1 2 3 4) 'a) ;Value 12: (1 2 3 4) prompt> (perm '(1 2 1) '(1 2 2)) ;Value: #f prompt> (perm '(1 2 3) '(2 3 1)) ;Value: #t prompt> (perm '(1 2 1) '(1 2 2 1)) ;Value: #f prompt> (perm '() '()) ;Value: #t prompt> (ordered? '(1 2 3 4 5 5 5 6 6 8 9)) ;Value: #t prompt> (ordered? '()) ;Value: #t prompt> (ordered? '(1 2 3 4 3 2 1)) ;Value: #f ```