Jump to content

Distinct power numbers: Difference between revisions

→‎{{header|AppleScript}}: Added a functionally composed variant.
(Added AppleScript.)
(→‎{{header|AppleScript}}: Added a functionally composed variant.)
Line 15:
 
=={{header|AppleScript}}==
===Procedural===
<lang applescript>on task()
script o
Line 38 ⟶ 39:
{{output}}
<lang applescript>{4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125}</lang>
 
 
===Functional===
Composing a solution from generic primitives, for speed of drafting, and ease of refactoring:
 
<lang applescript>use framework "Foundation"
use scripting additions
 
 
------------------ DISTINCT POWER VALUES -----------------
 
-- distinctPowers :: [Int] -> [Int]
on distinctPowers(xs)
script powers
on |λ|(a, x)
script integerPower
on |λ|(b, y)
b's setByAddingObject:((x ^ y) as integer)
end |λ|
end script
foldl(integerPower, a, xs)
end |λ|
end script
sort(foldl(powers, ¬
current application's NSSet's alloc's init(), xs)'s ¬
allObjects())
end distinctPowers
 
 
--------------------------- TEST -------------------------
on run
distinctPowers(enumFromTo(2, 5))
end run
 
 
------------------------- GENERIC ------------------------
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
 
-- sort :: Ord a => [a] -> [a]
on sort(xs)
((current application's NSArray's arrayWithArray:xs)'s ¬
sortedArrayUsingSelector:"compare:") as list
end sort</lang>
{{Out}}
<pre>{4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125}</pre>
 
=={{header|Go}}==
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.