Permutations: Difference between revisions

(→‎{{header|Erlang}}: List comprehension form)
Line 900:
F = fun(L) -> G = fun(_, []) -> [[]]; (F, L) -> [[X|Y] || X<-L, Y<-F(F, L--X)] end, G(G, L) end.
</lang>
NaïveMore andefficient ineffectivezipper implementation:
<lang Erlang>-module(permute).
 
-export([permute/1]).
-import(lists, [append/1, map/2, seq/2, split/2]).
 
permute( [H|T] ) -> [[]];
%% insert element E into list L immediately after the item at position N
permute(L) -> permute(L, []).
%% (N=0 prepends E to the list)
 
insert( L, N, E ) ->
% Use zipper to pick up first element of permutation
{H, T} = split( N, L ),
permute([], _) -> [];
append( [H, [E], T] ).
permute([H|T], R) ->
% place current member in front of all permutation of
% all permutations of rest of set - both sides of zipper
prepend(H, permute(lists:reverse(R, T)))
% go further in zipper
++ permute( T, ))[H|R]).
 
prepend(_, []) -> [];
% Return a list of all the permutations of the given list
permuteprepend(X, [H|T] ) -> [[X|H] | prepend(X, T)];.
permute( [H|T] ) ->
append( map( fun(P) ->
map( fun(N) ->
insert(P, N, H)
end,
seq( 0, length(P) ))
end,
permute( T ))).
</lang>
 
Anonymous user