I wrote a function that receives a list and returns a list of all its permutations. It works like:
- The permutations of a one-element list is a list of itself.
- The permutations of an n-element list are each element followed by the permutations of the list with the element removed.
(define (remove-nth lst n) ; remove the nth element from a list lst
(append (take lst n)
(drop lst (+ 1 n))))
(define (perm lst) ; a list of all permutations of lst
(if (null? (cdr lst))
(list lst)
(apply append (map (lambda (i)
(map (lambda (sublst) (cons (list-ref lst i)
sublst))
(perm (remove-nth lst i))))
(range (length lst))))))
Example:
> (perm '(1 2 3))
'((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))
Can it be made tail-recursive?
P.S. I know there is a permutations
function in Racket. While it is tail-recursive, it uses a different algorithm. I'm curious if the one I wrote can also be made tail-recursive.