Permutations: Difference between revisions

Line 429:
(44444, 333, 22, 1)
</pre>
 
 
=={{header|AppleScript}}==
 
{{trans|JavaScript}}
 
 
<lang AppleScript>-- permutations :: [a] -> [[a]]
on permutations(xs)
script mf
on lambdaX(x)
set mf to mf of my closure
concatMap(mClosure(mf's lambdaYs, {x:x}), ¬
permutations(delete1(x, xs of my closure)))
end lambdaX
on lambdaYs(ys)
{{my closure's x} & ys}
end lambdaYs
end script
if length of xs > 0 then
concatMap(mClosure(mf's lambdaX, {mf:mf, xs:xs}), xs)
else
{{}}
end if
end permutations
 
 
-- TEST
on run
permutations({"aardvarks", "eat", "ants"})
end run
 
 
-- GENERIC LIBRARY FUNCTIONS
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
script mf
on append(a, b)
a & b
end append
end script
foldl(mf's append, {}, map(f, xs))
end concatMap
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
set mf to mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to mf's lambda(item i of xs, i, xs)
end repeat
return lst
end map
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
set mf to mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to mf's lambda(v, item i of xs, i, xs)
end repeat
return v
end foldl
 
-- delete :: a -> [a] -> [a]
on delete1(x, xs)
script mf
on Eq(a, b)
a = b
end Eq
end script
deleteBy(mf's Eq, x, xs)
end delete1
 
-- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
on deleteBy(fnEq, x, xs)
if length of xs > 0 then
set mf to mReturn(fnEq)
set {h, t} to uncons(xs)
if mf's lambda(x, h) then
t
else
{h} & deleteBy(fnEq, x, t)
end if
else
{}
end if
end deleteBy
 
-- uncons :: [a] -> Maybe (a, [a])
on uncons(xs)
set lng to length of xs
if lng > 0 then
if lng > 1 then
{item 1 of xs, items 2 thru -1 of xs}
else
{item 1 of xs, {}}
end if
else
{missing value, {}}
end if
end uncons
 
-- Lift 2nd class function into 1st class wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then return f
script
property lambda : f
end script
end mReturn
 
-- Handler -> Record -> Script
on mClosure(f, recBindings)
script
property closure : recBindings
property lambda : f
end script
end mClosure
</lang>
 
{{Out}}
 
<pre>{{"aardvarks", "eat", "ants"}, {"aardvarks", "ants", "eat"},
{"eat", "aardvarks", "ants"}, {"eat", "ants", "aardvarks"},
{"ants", "aardvarks", "eat"}, {"ants", "eat", "aardvarks"}}</pre>
 
=={{header|AutoHotkey}}==
9,659

edits