September Morn Update

This commit is contained in:
Ingy döt Net 2019-09-12 10:33:56 -07:00
parent 4e2d22a71d
commit aac6731f2c
6856 changed files with 141342 additions and 21127 deletions

View file

@ -0,0 +1,178 @@
/* ARM assembly Raspberry PI */
/* program multtable.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ MAXI, 12
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
sBlanc1: .asciz " "
sBlanc2: .asciz " "
sBlanc3: .asciz " "
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
@ display first line
mov r4,#0
1: @ begin loop
mov r0,r4
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
mov r2,#0 @ final zéro
strb r2,[r1,r0] @ on display value
ldr r0,iAdrsMessValeur
bl affichageMess @ display message
cmp r4,#10 @ one or two digit in résult
ldrgt r0,iAdrsBlanc2 @ two display two spaces
ldrle r0,iAdrsBlanc3 @ one display 3 spaces
bl affichageMess @ display message
add r4,#1 @ increment counter
cmp r4,#MAXI
ble 1b @ loop
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display carriage return
mov r5,#1 @ line counter
2: @ begin loop lines
mov r0,r5 @ display column 1 with N° line
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
mov r2,#0 @ final zéro
strb r2,[r1,r0]
ldr r0,iAdrsMessValeur
bl affichageMess @ display message
cmp r5,#10 @ one or two digit in N° line
ldrge r0,iAdrsBlanc2
ldrlt r0,iAdrsBlanc3
bl affichageMess
mov r4,#1 @ counter column
3: @ begin loop columns
mul r0,r4,r5 @ multiplication
mov r3,r0 @ save résult
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
mov r2,#0
strb r2,[r1,r0]
ldr r0,iAdrsMessValeur
bl affichageMess @ display message
cmp r3,#100 @ 3 digits in résult ?
ldrge r0,iAdrsBlanc1 @ yes, display one space
bge 4f
cmp r3,#10 @ 2 digits in result
ldrge r0,iAdrsBlanc2 @ yes display 2 spaces
ldrlt r0,iAdrsBlanc3 @ no display 3 spaces
4:
bl affichageMess @ display message
add r4,#1 @ increment counter column
cmp r4,r5 @ < counter lines
ble 3b @ loop
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display carriage return
add r5,#1 @ increment line counter
cmp r5,#MAXI @ MAXI ?
ble 2b @ loop
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsBlanc1: .int sBlanc1
iAdrsBlanc2: .int sBlanc2
iAdrsBlanc3: .int sBlanc3
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0 */
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
mov r3,#0xCCCD @ r3 <- magic_number lower
movt r3,#0xCCCC @ r3 <- magic_number upper
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function

View file

@ -0,0 +1,14 @@
100 PROGRAM "Multipli.bas"
110 TEXT 80
120 PRINT TAB(7);
130 FOR I=1 TO 12
140 PRINT USING " ###":I;
150 NEXT
160 PRINT AT 2,5:"----------------------------------------------------"
170 FOR I=1 TO 12
180 PRINT USING "### |":I;:PRINT TAB(I*4+3);
190 FOR J=I TO 12
200 PRINT USING " ###":I*J;
210 NEXT
220 PRINT
230 NEXT

View file

@ -0,0 +1,30 @@
import Data.Maybe (fromMaybe, maybe)
import Data.Bool (bool)
table :: [Int] -> [[Maybe Int]]
table xs =
let axis = Just <$> xs
in (Nothing : axis) :
zipWith
(:)
axis
[ [ bool (Just (x * y)) Nothing (x > y)
| y <- xs ]
| x <- xs ]
-- TEST ---------------------------------------------------
main :: IO ()
main =
(putStrLn . unlines) $
(showTable . table) <$> [[13 .. 20], [1 .. 12], [95 .. 100]]
-- FORMATTING ---------------------------------------------
showTable :: [[Maybe Int]] -> String
showTable xs =
let w = 1 + (length . show) (fromMaybe 0 $ (last . last) xs)
gap = replicate w ' '
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
in unlines $ head rows : [] : tail rows
rjust :: Int -> Char -> String -> String
rjust n c = (drop . length) <*> (replicate n c ++)

View file

@ -0,0 +1,11 @@
import Data.List (groupBy)
import Data.Function (on)
import Control.Monad (join)
main :: IO ()
main =
mapM_ print $
fmap (uncurry (*)) <$>
groupBy
(on (==) fst)
(filter (uncurry (>=)) $ join ((<*>) . fmap (,)) [1 .. 12])

View file

@ -1,26 +0,0 @@
import Data.Monoid ((<>))
import Data.List (intercalate, transpose)
multTable :: Int -> [[String]]
multTable n =
let xs = [1 .. n]
in xs >>=
\x ->
[ show x <> ":" :
(xs >>=
\y ->
[ if y < x
then mempty
else show (x * y)
])
]
table :: String -> [[String]] -> [String]
table delim rows =
let justifyRight c n s = drop (length s) (replicate n c <> s)
in intercalate delim <$>
transpose
((fmap =<< justifyRight ' ' . maximum . fmap length) <$> transpose rows)
main :: IO ()
main = (putStrLn . unlines . table " " . multTable) 12

View file

@ -0,0 +1,42 @@
/**
Multiplication table, in Neko
Tectonics:
nekoc multiplication-table.neko
neko multiplication-table
*/
var sprintf = $loader.loadprim("std@sprintf", 2);
var i, j;
i = 1;
$print(" X |");
while i < 13 {
$print(sprintf("%4d", i));
i += 1;
}
$print("\n");
$print(" ---+");
i = 1;
while i < 13 {
$print("----");
i += 1;
}
$print("\n");
j = 1;
while j < 13 {
$print(sprintf("%3d", j));
$print(" |");
i = 1;
while i < 13 {
if j > i {
$print(" ");
} else {
$print(sprintf("%4d", i*j));
}
i += 1;
}
$print("\n");
j += 1;
}

View file

@ -0,0 +1,103 @@
'''Multiplication table
1. by list comprehension (mulTable ),
2. by list monad. (mulTable2)'''
from itertools import chain
# mulTable :: Int -> String
def mulTable(n):
'''A multiplication table of dimension n,
without redundant entries beneath
the diagonal of squares.'''
# colWidth :: Int
colWidth = len(str(n * n))
# pad :: String -> String
def pad(s):
return s.rjust(colWidth, ' ')
xs = enumFromTo(1)(n)
return unlines([
pad(str(y) + ':') + unwords([
pad(str(x * y) if x >= y else '')
for x in xs
]) for y in xs
])
# mulTable2 :: Int -> String
def mulTable2(n):
'''Identical to mulTable above,
but the list comprehension is directly
desugared to an equivalent list monad expression.'''
# colWidth :: Int
colWidth = len(str(n * n))
# pad :: String -> String
def pad(s):
return s.rjust(colWidth, ' ')
xs = enumFromTo(1)(n)
return unlines(
bind(xs)(lambda y: [
pad(str(y) + ':') + unwords(
bind(xs)(lambda x: [
pad(str(x * y) if x >= y else '')
])
)
])
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test'''
for s, f in [
('list comprehension', mulTable),
('list monad', mulTable2)
]:
print(
'By ' + s + ' (' + f.__name__ + '):\n\n',
f(12).strip() + '\n'
)
# GENERIC -------------------------------------------------
# bind (>>=) :: [a] -> (a -> [b]) -> [b]
def bind(xs):
'''The injection operator for the list monad.
Equivalent to concatMap with its arguments flipped.'''
return lambda f: list(
chain.from_iterable(
map(f, xs)
)
)
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# unlines :: [String] -> String
def unlines(xs):
'''A newline-delimited string derived from a list of lines.'''
return '\n'.join(xs)
# unwords :: [String] -> String
def unwords(xs):
'''A space-delimited string derived from a list of words.'''
return ' '.join(xs)
if __name__ == '__main__':
main()

View file

@ -0,0 +1,267 @@
'''Generalised multiplication tables'''
import collections
import itertools
import inspect
# table :: Int -> [[Maybe Int]]
def table(xs):
'''An option-type model of a multiplication table:
a tabulation of Just(x * y) values for all
pairings (x, y) of integers in xs where x > y,
and Nothing values where y <= x.
'''
axis = fmap(Just)(xs)
return list(cons(
cons(Nothing())(axis)
)(zipWith(cons)(axis)([
[
Nothing() if y > x else Just(x * y)
for x in xs
]
for y in xs
])))
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test'''
print('\n\n'.join(
fmap(fmap(fmap(showTable)(table))(
liftA2(enumFromTo)(fst)(snd)
))(
[(13, 20), (1, 12), (95, 100)]
)
))
# DISPLAY -------------------------------------------------
# showTable :: [[Maybe Int]] -> String
def showTable(xs):
'''A stringification of an abstract model
of a multiplication table.
'''
w = 1 + len(str(last(last(xs))['Just']))
gap = ' ' * w
rows = fmap(fmap(concat)(
fmap(maybe(gap)(
fmap(justifyRight(w)(' '))(str)
))
))(xs)
return unlines([rows[0]] + [''] + rows[1:])
# GENERIC -------------------------------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.'''
return {'type': 'Maybe', 'Nothing': True}
# concat :: [[a]] -> [a]
# concat :: [String] -> String
def concat(xs):
'''The concatenation of all the elements
in a list or iterable.'''
chain = itertools.chain
def f(ys):
zs = list(chain(*ys))
return ''.join(zs) if isinstance(ys[0], str) else zs
return (
f(xs) if isinstance(xs, list) else (
chain.from_iterable(xs)
)
) if xs else []
# cons :: a -> [a] -> [a]
def cons(x):
'''Construction of a list from x as head,
and xs as tail.'''
chain = itertools.chain
return lambda xs: [x] + xs if (
isinstance(xs, list)
) else chain([x], xs)
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
'''A curried function derived
from an uncurried function.'''
signature = inspect.signature
if 1 < len(signature(f).parameters):
return lambda x: lambda y: f(x, y)
else:
return f
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# fmap :: Functor f => (a -> b) -> f a -> f b
def fmap(f):
'''A function f mapped over a functor.'''
def go(x):
defaultdict = collections.defaultdict
return defaultdict(list, [
('list', fmapList),
# ('iter', fmapNext),
# ('Either', fmapLR),
# ('Maybe', fmapMay),
# ('Tree', fmapTree),
# ('tuple', fmapTuple),
('function', fmapFn),
('type', fmapFn)
])[
typeName(x)
](f)(x)
return lambda v: go(v)
# fmapFn :: (a -> b) -> (r -> a) -> r -> b
def fmapFn(f):
'''fmap over a function.
The composition of f and g.
'''
return lambda g: lambda x: f(g(x))
# fmapList :: (a -> b) -> [a] -> [b]
def fmapList(f):
'''fmap over a list.
f lifted to a function over a list.
'''
return lambda xs: list(map(f, xs))
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# justifyRight :: Int -> Char -> String -> String
def justifyRight(n):
'''A string padded at left to length n,
using the padding character c.
'''
return lambda c: lambda s: s.rjust(n, c)
# last :: [a] -> a
def last(xs):
'''The last element of a non-empty list.'''
return xs[-1]
# liftA2 :: (a -> b -> c) -> f a -> f b -> f c
def liftA2(f):
'''Lift a binary function to the type of a.'''
def go(a, b):
defaultdict = collections.defaultdict
return defaultdict(list, [
# ('list', liftA2List),
# ('Either', liftA2LR),
# ('Maybe', liftA2May),
# ('Tree', liftA2Tree),
# ('tuple', liftA2Tuple),
('function', liftA2Fn)
])[
typeName(a)
](f)(a)(b)
return lambda a: lambda b: go(a, b)
# liftA2Fn :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c
def liftA2Fn(op):
'''Lift a binary function to a composition
over two other functions.
liftA2 (*) (+ 2) (+ 3) 7 == 90
'''
def go(f, g):
return lambda x: curry(op)(
f(x)
)(g(x))
return lambda f: lambda g: go(f, g)
# maybe :: b -> (a -> b) -> Maybe a -> b
def maybe(v):
'''Either the default value v, if m is Nothing,
or the application of f to x,
where m is Just(x).
'''
return lambda f: lambda m: v if m.get('Nothing') else (
f(m.get('Just'))
)
# typeName :: a -> String
def typeName(x):
'''Name string for a built-in or user-defined type.
Selector for type-specific instances
of polymorphic functions.
'''
if isinstance(x, dict):
return x.get('type') if 'type' in x else 'dict'
else:
return 'iter' if hasattr(x, '__next__') else (
type(x).__name__
)
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
'''A function over a pair of arguments,
derived from a vanilla or curried function.
'''
signature = inspect.signature
if 1 < len(signature(f).parameters):
return lambda xy: f(*xy)
else:
return lambda x, y: f(x)(y)
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.
'''
return '\n'.join(xs)
# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
'''A list constructed by zipping with a
custom function, rather than with the
default tuple constructor.
'''
return lambda xs: lambda ys: (
map(uncurry(f), xs, ys)
)
# MAIN ---
if __name__ == '__main__':
main()

View file

@ -0,0 +1,18 @@
//Multiplication Table
print("%5s".format("|"))
for (i <- 1 to 12) print("%5d".format(i))
println()
println("-----" * 13)
for (i <- 1 to 12) {
print("%4d|".format(i))
for (j <- 1 to 12) {
if (i <= j)
print("%5d".format(i * j))
else
print("%5s".format(""))
}
println("")
}

View file

@ -0,0 +1,18 @@
implicit def intToString(i: Int) = i.toString
val cell = (x:String) => print("%5s".format(x))
for {
i <- 1 to 14
j <- 1 to 14
}
yield {
(i, j) match {
case (i, 13) => cell("|")
case (i, 14) if i > 12 => cell("\n")
case (13, j) => cell("-----")
case (i, 14) => cell(i + "\n")
case (14, j) => cell(j)
case (i, j) if i <= j => cell(i*j)
case (i, j) => cell("-")
}
}

View file

@ -1,48 +0,0 @@
//Multiplication Table
object mulTable{
def main( args:Array[String] ){
print(" |") //Horizontal row
for( i <- 1 to 12 )
if( i<10 )
print( " " + i )
else
print(" " + i )
println("")
println("---------------------------------------------------------------------")
for( i <- 1 to 12 ){
if( i<10 ) //Vertical column
print(" " + i + "|" )
else
print(" " + i + "|" )
for( j <- 1 to 12 ){
if( i*j < 10 ){
if( i<=j )
print(" " + i*j )
else
print(" ")
}
else if( i*j < 100 ){
if( i<=j )
print(" " + i*j )
else
print(" ")
}
else{
if( i<=j )
print(" " + i*j )
else
print(" ")
}
}
println("")
}
}
}