September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -0,0 +1,107 @@
-- 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
on lambda(residue)
set {divided, remainder} to quotRem(residue, intBase)
{valid:divided > 0, value:(item (remainder + 1) of strDigits), new:divided}
end lambda
end script
reverse of unfoldr(nextDigit, n) as string
end inBaseDigits
-- OTHER FUNCTIONS DERIVABLE FROM inBaseDigits
-- inUpperHex :: Int -> String
on inUpperHex(n)
inBaseDigits("0123456789ABCDEF", n)
end inUpperHex
-- inDevanagariDecimal :: Int -> String
on inDevanagariDecimal(n)
inBaseDigits("०१२३४५६७८९", n)
end inDevanagariDecimal
-- TEST
on run
script
on lambda(x)
{{binary:toBase(2, x), octal:toBase(8, x), hex:toBase(16, x)}, ¬
{upperHex:inUpperHex(x), dgDecimal:inDevanagariDecimal(x)}}
end lambda
end script
map(result, [255, 240])
end run
-- GENERIC FUNCTIONS
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
set mf to mReturn(f)
set lst to {}
set recM to mf's lambda(v)
repeat while (valid of recM) is true
set end of lst to value of recM
set recM to mf's lambda(new of recM)
end repeat
lst & value of recM
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
set end of lst to lambda(item i of xs, i, xs)
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
property lambda : f
end script
end if
end mReturn
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set mp to mReturn(p)
set v to x
tell mReturn(f)
repeat until mp's lambda(v)
set v to lambda(v)
end repeat
end tell
return v
end |until|

View file

@ -0,0 +1,2 @@
{{{binary:"11111111", octal:"377", hex:"ff"}, {upperHex:"FF", dgDecimal:"२५५"}},
{{binary:"11110000", octal:"360", hex:"f0"}, {upperHex:"F0", dgDecimal:"२४०"}}}

View file

@ -0,0 +1,52 @@
import Data.List (unfoldr)
import Data.Char (intToDigit)
inBaseDigits :: [Char] -> Int -> String
inBaseDigits ds n =
let base = length ds
in reverse $
unfoldr
(\x ->
(if x > 0
then let (d, r) = quotRem x base
in Just (ds !! r, d)
else Nothing))
n
inLowerHex :: Int -> String
inLowerHex = inBaseDigits "0123456789abcdef"
inUpperHex :: Int -> String
inUpperHex = inBaseDigits "0123456789ABCDEF"
inBinary :: Int -> String
inBinary = inBaseDigits "01"
inOctal :: Int -> String
inOctal = inBaseDigits "01234567"
inDevanagariDecimal :: Int -> String
inDevanagariDecimal = inBaseDigits "०१२३४५६७८९"
inHinduArabicDecimal :: Int -> String
inHinduArabicDecimal = inBaseDigits "٠١٢٣٤٥٦٧٨٩"
toBase :: Int -> Int -> String
toBase intBase n =
if (intBase < 36) && (intBase > 0)
then inBaseDigits (take intBase (['0' .. '9'] ++ ['a' .. 'z'])) n
else []
main :: IO ()
main =
mapM_ putStrLn $
[ inLowerHex
, inUpperHex
, inBinary
, inOctal
, toBase 16
, toBase 2
, inDevanagariDecimal
, inHinduArabicDecimal
] <*>
[254]

View file

@ -0,0 +1,93 @@
(() => {
'use strict';
// toBase :: Int -> Int -> String
const toBase = (intBase, n) =>
intBase < 36 && intBase > 0 ?
inBaseDigits('0123456789abcdef'.substr(0, intBase), n) : [];
// inBaseDigits :: String -> Int -> [String]
const inBaseDigits = (digits, n) => {
const intBase = digits.length;
return unfoldr(maybeResidue => {
const [divided, remainder] = quotRem(maybeResidue.new, intBase);
return {
valid: divided > 0,
value: digits[remainder],
new: divided
};
}, n)
.reverse()
.join('');
};
// GENERIC FUNCTIONS
// unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
const unfoldr = (mf, v) => {
var xs = [];
return (until(
m => !m.valid,
m => {
const m2 = mf(m);
return (
xs = xs.concat(m2.value),
m2
);
}, {
valid: true,
value: v,
new: v,
}
), xs);
};
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
}
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = (m, n) => [Math.floor(m / n), m % n];
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
// OTHER FUNCTIONS DERIVABLE FROM inBaseDigits
// inLowerHex :: Int -> String
const inLowerHex = curry(inBaseDigits)('0123456789abcdef');
/// inUpperHex :: Int -> String
const inUpperHex = curry(inBaseDigits)('0123456789ABCDEF');
// inOctal :: Int -> String
const inOctal = curry(inBaseDigits)('01234567');
// inDevanagariDecimal :: Int -> String
const inDevanagariDecimal = curry(inBaseDigits)('०१२३४५६७८९');
// TESTS
// testNumber :: [Int]
const testNumbers = [255, 240];
return testNumbers.map(n => show({
binary: toBase(2, n),
base5: toBase(5, n),
hex: toBase(16, n),
upperHex: inUpperHex(n),
octal: inOctal(n),
devanagariDecimal: inDevanagariDecimal(n)
}));
})();

View file

@ -10,7 +10,7 @@ def convert(base):
end
end;
# input string is converted from "base" to an integer, wihtin limits
# input string is converted from "base" to an integer, within limits
# of the underlying arithmetic operations, and without error-checking:
def to_i(base):
explode

View file

@ -0,0 +1,7 @@
# 26 in base 16 or 2
base(16, 26)
base(2, 26)
# Parse to integer
parse(Int, "1a", 16)
parse(Int, "101101", 2)

View file

@ -0,0 +1,45 @@
// version 1.0.6
fun min(x: Int, y: Int) = if (x < y) x else y
fun convertToBase(n: Int, b: Int): String {
if (n < 2 || b < 2 || b == 10 || b > 36) return n.toString() // leave as decimal
val sb = StringBuilder()
var digit: Int
var nn = n
while (nn > 0) {
digit = nn % b
if (digit < 10) sb.append(digit)
else sb.append((digit + 87).toChar())
nn /= b
}
return sb.reverse().toString()
}
fun convertToDecimal(s: String, b: Int): Int {
if (b !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36")
if (b == 10) return s.toInt()
val t = s.toLowerCase()
var result = 0
var digit: Int
var multiplier = 1
for (i in t.length - 1 downTo 0) {
digit = -1
if (t[i] >= '0' && t[i] <= min(57, 47 + b).toChar())
digit = t[i].toInt() - 48
else if (b > 10 && t[i] >= 'a' && t[i] <= min(122, 87 + b).toChar())
digit = t[i].toInt() - 87
if (digit == -1) throw IllegalArgumentException("Invalid digit present")
if (digit > 0) result += multiplier * digit
multiplier *= b
}
return result
}
fun main(args: Array<String>) {
for (b in 2..36) {
val s = convertToBase(36, b)
val f = "%2d".format(b)
println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}")
}
}

View file

@ -1,12 +0,0 @@
Input to this program (bases must be positive integers > 1):
x is required (it may have a sign).
toBase the base to convert X to.
inBase the base X is expressed in.
If X has a leading sign, it is maintained (kept) after conversion.
toBase or inBase can be a comma (,) which causes the default
of 10 to be used. The limits of bases are: 2 90.

View file

@ -1,37 +0,0 @@
/*REXX pgm converts integers from one base to another (base 2 ──► 90). */
@abc = 'abcdefghijklmnopqrstuvwxyz' /*the lowercase (Latin) alphabet.*/
parse upper var @abc @abcU /*uppercase a version of @abc. */
@@ = 0123456789 || @abc || @abcU /*prefix 'em with numeric digits.*/
@@ = @@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬' /*add some special chars as well.*/
/* [↑] all chars must be viewable*/
numeric digits 3000 /*what da hey, support gihugeics.*/
maxB=length(@@) /*max base (radix) supported here*/
parse arg x toB inB 1 ox . 1 sigX 2 x2 . /*get: 3 args, origX, sign···*/
if pos(sigX,"+-")\==0 then x=x2 /*Does X have a leading sign? */
else sigX= /*Nope. No leading sign for X. */
if x=='' then call erm /*if no X number, issue error.*/
if toB=='' | toB=="," then toB=10 /*if skipped, assume default (10)*/
if inB=='' | inB=="," then inB=10 /* " " " " " */
if inB<2 | inb>maxB | \datatype(inB,'W') then call erb 'inBase ' inB
if toB<2 | toB>maxB | \datatype(toB,'W') then call erb 'toBase ' toB
#=0 /*result of converted X (base 10)*/
do j=1 for length(x) /*convert X, base inB ──► base 10*/
?=substr(x,j,1) /*pick off a numeral/digit from X*/
_=pos(?, @@) /*calculate this numeral's value.*/
if _==0 | _>inB then call erd x /*_ character an illegal numeral?*/
#=#*inB+_-1 /*build a new number, dig by dig.*/
end /*j*/ /* [↑] this also verifies digits*/
y= /*the value of X in base B. */
do while # >= toB /*convert #, base 10 ──► base toB*/
y=substr(@@, (#//toB)+1, 1)y /*construct the output number. */
#=#%toB /*··· and whittle # down also. */
end /*while*/ /* [↑] process leaves a residual*/
/* [↓] Y is the residual*/
y=sigX || substr(@@, #+1, 1)y /*prepend the sign if it existed.*/
say ox "(base" inB')' center('is',20) y "(base" toB')'
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────one─liner subroutines───────────────*/
erb: call ser 'illegal' arg(1)", it must be in the range: 2──►"maxB
erd: call ser 'illegal digit/numeral ['?"] in: " x
erm: call ser 'no argument specified.'
ser: say; say '***error!***'; say arg(1); exit 13

View file

@ -1,2 +0,0 @@
s = 26.to_s(16) # returns the string 1a
i = '1a'.to_i(16) # returns the integer 26

View file

@ -1 +0,0 @@
"59".to_i(7) # returns 5, but this is probably not what you wanted

View file

@ -1,32 +0,0 @@
module BaseConvert
DIGITS = [*"0".."9", *"a".."z"]
def baseconvert(str, basefrom, baseto)
dec2base(base2dec(str, basefrom), baseto)
end
def base2dec(str, base)
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
str.to_s.downcase.each_char.inject(0) do |res, c|
idx = DIGITS[0,base].index(c)
idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}"
res = res * base + idx
end
end
def dec2base(n, base)
return "0" if n == 0
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
res = []
while n > 0
n, r = n.divmod(base)
res.unshift(DIGITS[r])
end
res.join
end
end
include BaseConvert
p dec2base(26, 16) # => "1a"
p base2dec("1a", 16) # => 26
p baseconvert("107h", 23, 7) # => "50664"

View file

@ -0,0 +1,2 @@
(26).toString(16) //--> "1a"
"1a".toInt(16) //-->26

View file

@ -0,0 +1 @@
"%x %,.2B".fmt(26,26) //-->"1a 1|1010"