OILS / demo / survey-arith.sh View on Github | oilshell.org

112 lines, 64 significant
1#!/usr/bin/env bash
2#
3# Survey arithmetic in various languages
4#
5# Usage:
6# demo/survey-arith.sh <function name>
7
8set -o nounset
9set -o pipefail
10set -o errexit
11
12# TODO:
13# - Test invariants
14# - OSH follows shells/awk/C
15# - YSH could disallow negative numbers
16
17divmod() {
18 echo 'Python'
19 python3 -c 'print(10 / -3); print(- 10 / 3)'
20 python3 -c 'print(10 // -3); print(- 10 // 3)'
21 python3 -c 'print(10 % -3); print(- 10 % 3); print (-10 % -3)'
22 python3 -c 'print(10.0 % -3.0); print(- 10.0 % 3.0); print (-10.0 % -3.0)'
23 echo
24
25 # Lua matches Python!
26 echo 'Lua'
27 lua -e 'print(10 / -3); print(- 10 / 3)'
28 lua -e 'print(10 // -3); print(- 10 // 3)'
29 lua -e 'print(10 % -3); print(- 10 % 3); print (-10 % -3)'
30 lua -e 'print(10.0 % -3.0); print(- 10.0 % 3.0); print (-10.0 % -3.0)'
31 echo
32
33 # JS and Awk match
34 echo 'JS'
35 nodejs -e 'console.log(10 / -3); console.log(- 10 / 3)'
36 nodejs -e 'console.log(10 % -3); console.log(- 10 % 3); console.log(-10 % -3);'
37 # no difference
38 #nodejs -e 'console.log(10.0 % -3.0); console.log(- 10.0 % 3.0); console.log(-10.0 % -3.0);'
39 echo
40
41 echo 'Perl'
42 perl -e 'print 10 / -3 . "\n"; print - 10 / 3 . "\n"'
43 # Perl modulus doesn't match Python/Lua or Awk/shell!
44 perl -e 'print 10 % -3 . "\n"; print - 10 % 3 . "\n"; print -10 % -3 . "\n"'
45 perl -e 'print 10.0 % -3.0 . "\n"; print - 10.0 % 3.0 . "\n"; print -10.0 % -3.0 . "\n"'
46 echo
47
48 echo 'Awk'
49 awk 'END { print(10 / -3); print (- 10 / 3) }' < /dev/null
50 awk 'END { print(10 % -3); print (- 10 % 3); print(-10 % -3) }' < /dev/null
51 echo
52
53 # bash only has integegers
54 for sh in bash dash zsh; do
55 echo $sh
56 $sh -c 'echo $((10 / -3)); echo $((- 10 / 3))'
57 $sh -c 'echo $((10 % -3)); echo $((- 10 % 3)); echo $((-10 % -3))'
58 echo
59 done
60}
61
62# TODO:
63# - Add Julia, Erlang, Elixir
64
65bigint() {
66 # Bigger than 2**64
67 local big=11112222333344445555666677778888999
68
69 # Big Int
70 echo 'python3'
71 python3 -c "print($big)"
72 echo
73
74 # Gets printed in scientific notation
75 echo 'node.js'
76 nodejs -e "console.log($big)"
77 echo
78
79 # Ditto, scientific
80 echo 'Lua'
81 lua -e "print($big)"
82 echo
83
84 # Scientific
85 echo Perl
86 perl -e "print $big"; echo
87 echo
88
89 # Awk loses precision somehow, not sure what they're doing
90 echo awk
91 awk -e "END { print $big }" < /dev/null
92 echo
93
94 local osh=_bin/cxx-dbg/osh
95 ninja $osh
96
97 for sh in dash bash mksh zsh $osh; do
98 echo $sh
99 $sh -c "echo \$(( $big ))" || true
100 echo
101 done
102
103 # Julia has big integers
104 echo 'Julia'
105 demo/julia.sh julia -e "print($big)"; echo
106 echo
107
108 # None of the interpreters reject invalid input! They tend to mangle the
109 # numbers.
110}
111
112"$@"