All permutations example in Erlang

Wondering how this compact Erlang code

 perms([]) -> [[]];
 perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])].

could look in Julia language.

Common Lisp apparently uses the same logic, but is more verbose:

(defun permute (list)
  (if list
    (mapcan #'(lambda (x)
		(mapcar #'(lambda (y) (cons x y))
			(permute (remove x list))))
	    list)
    '(()))) ; else
 
(print (permute '(A B Z)))
perms(l) = isempty(l) ? [l] : [[x; y] for x in l for y in perms(setdiff(l, x))]

Thanks Bogumił!

I was close… :

  • wrote isempty(l) ? [].
  • put a comma in [x,y], gives no error, but quite different output

Maybe good for a training based on debugging.

The issue is that you want to return the collection of permutations. Just returning [] does not return any permutation, while you want to return a single empty permutation [[]]. The reason I use [l] and not [[]] is that [l] does a proper inference of type of the collection to be produced (and we know that l is empty so [l] will contain one empty collection but with the benefit that it has a proper element type).

Allright!