Permutations: Difference between revisions

Content added Content deleted
No edit summary
(→‎{{header|AppleScript}}: Simplified closures, updated library functions)
Line 442: Line 442:
(Functional ES5 version)
(Functional ES5 version)


<lang AppleScript>
<lang AppleScript>on run
on run
permutations({"aardvarks", "eat", "ants"})
permutations({"aardvarks", "eat", "ants"})
Line 451: Line 450:
-- permutations :: [a] -> [[a]]
-- permutations :: [a] -> [[a]]
on permutations(xs)
on permutations(xs)
script mf
script firstElement
on lambdaX(x)
on lambda(x)
set mf to mf of my closure
script tailElements
concatMap(mClosure(mf's lambdaYs, {x:x}), ¬
on lambda(ys)
permutations(|delete|(x, xs of my closure)))
{{x} & ys}
end lambdaX
end lambda
end script
on lambdaYs(ys)
{{my closure's x} & ys}
concatMap(tailElements, permutations(|delete|(x, xs)))
end lambdaYs
end lambda
end script
end script
if length of xs > 0 then
if length of xs > 0 then
concatMap(mClosure(mf's lambdaX, {mf:mf, xs:xs}), xs)
concatMap(firstElement, xs)
else
else
{{}}
{{}}
end if
end if
end permutations
end permutations





Line 475: Line 475:
-- concatMap :: (a -> [b]) -> [a] -> [b]
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
on concatMap(f, xs)
script mf
script append
on append(a, b)
on lambda(a, b)
a & b
a & b
end append
end lambda
end script
end script
foldl(mf's append, {}, map(f, xs))
foldl(append, {}, map(f, xs))
end concatMap
end concatMap


Line 508: Line 509:
-- delete :: a -> [a] -> [a]
-- delete :: a -> [a] -> [a]
on |delete|(x, xs)
on |delete|(x, xs)
script mf
script Eq
on Eq(a, b)
on lambda(a, b)
a = b
a = b
end Eq
end lambda
end script
end script
deleteBy(mf's Eq, x, xs)
deleteBy(Eq, x, xs)
end |delete|
end |delete|


Line 520: Line 521:
on deleteBy(fnEq, x, xs)
on deleteBy(fnEq, x, xs)
if length of xs > 0 then
if length of xs > 0 then
set mf to mReturn(fnEq)
set {h, t} to uncons(xs)
set {h, t} to uncons(xs)
if mf's lambda(x, h) then
if lambda(x, h) of mReturn(fnEq) then
t
t
else
else
Line 546: Line 546:
end uncons
end uncons


-- Lift 2nd class function into 1st class wrapper
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
-- mReturn :: Handler -> Script
on mReturn(f)
on mReturn(f)
if class of f is script then return f
if class of f is script then
script
f
else
property lambda : f
end script
script
property lambda : f
end script
end if
end mReturn
end mReturn


-- Handler -> Record -> Script
on mClosure(f, recBindings)
script
property closure : recBindings
property lambda : f
end script
end mClosure
</lang>
</lang>