RosettaCodeData/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript

97 lines
2.4 KiB
AppleScript
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
-- toBase :: Int -> Int -> String
on toBase(intBase, n)
if (intBase < 36) and (intBase > 0) then
inBaseDigits(items 1 thru intBase of "0123456789abcdefghijklmnopqrstuvwxyz", n)
else
"not defined for base " & (n as string)
end if
end toBase
-- inBaseDigits :: String -> Int -> [String]
on inBaseDigits(strDigits, n)
set intBase to length of strDigits
script nextDigit
2018-06-22 20:57:24 +00:00
on |λ|(residue)
2017-09-23 10:01:46 +02:00
set {divided, remainder} to quotRem(residue, intBase)
2018-06-22 20:57:24 +00:00
if divided > 0 then
{just:(item (remainder + 1) of strDigits), new:divided, nothing:false}
else
{nothing:true}
end if
2017-09-23 10:01:46 +02:00
2018-06-22 20:57:24 +00:00
end |λ|
2017-09-23 10:01:46 +02:00
end script
reverse of unfoldr(nextDigit, n) as string
end inBaseDigits
2018-06-22 20:57:24 +00:00
-- OTHER FUNCTIONS DERIVABLE FROM inBaseDigits -------------------------------
2017-09-23 10:01:46 +02:00
-- inUpperHex :: Int -> String
on inUpperHex(n)
inBaseDigits("0123456789ABCDEF", n)
end inUpperHex
-- inDevanagariDecimal :: Int -> String
on inDevanagariDecimal(n)
inBaseDigits("०१२३४५६७८९", n)
end inDevanagariDecimal
2018-06-22 20:57:24 +00:00
-- TEST ----------------------------------------------------------------------
2017-09-23 10:01:46 +02:00
on run
script
2018-06-22 20:57:24 +00:00
on |λ|(x)
2017-09-23 10:01:46 +02:00
{{binary:toBase(2, x), octal:toBase(8, x), hex:toBase(16, x)}, ¬
{upperHex:inUpperHex(x), dgDecimal:inDevanagariDecimal(x)}}
2018-06-22 20:57:24 +00:00
end |λ|
2017-09-23 10:01:46 +02:00
end script
map(result, [255, 240])
end run
2018-06-22 20:57:24 +00:00
-- GENERIC FUNCTIONS ---------------------------------------------------------
2017-09-23 10:01:46 +02:00
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
set lst to {}
2018-06-22 20:57:24 +00:00
set recM to {nothing:false, new:v}
tell mReturn(f)
repeat while (not (nothing of recM))
set recM to |λ|(new of recM)
if not nothing of recM then set end of lst to just of recM
end repeat
end tell
lst
2017-09-23 10:01:46 +02:00
end unfoldr
-- quotRem :: Integral a => a -> a -> (a, a)
on quotRem(m, n)
{m div n, m mod n}
end quotRem
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
2018-06-22 20:57:24 +00:00
set end of lst to |λ|(item i of xs, i, xs)
2017-09-23 10:01:46 +02:00
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
2018-06-22 20:57:24 +00:00
property |λ| : f
2017-09-23 10:01:46 +02:00
end script
end if
end mReturn