modulus<i32>
Translation status: English reader-locale proof. Term names and code fences follow the en pack; supporting prose may still be English.
Signed wrapping integers: the ring of 2^W values with signed representatives, as in a Java hash.
Syntax: wrapping<i32>
Category#
arithmetic
Related#
Examples#
radix/corpus/reference/operator-group/modulus-i32/modular-word-signed.fab (canonical · operator-group)#
Signed wrapping integers: the ring of 2^W values with signed representatives, as in a Java hash.
# =============================================================================
# wrapping<i32> — Signed wrapping integers: the ring of 2^W values with signed representatives.
# =============================================================================
#
# What this teaches:
# • Signed ring — `wrapping<i8>` holds -128..127 and wraps at both ends:
# 127 + 1 is -128, and `-128 / -1` is -128 again.
# • Floor division — `/` and `%` floor on the representatives: -7 / 2 is -4
# and -7 % 2 is 1.
# • Arithmetic shift and complement — `⇒` keeps the sign (-8 ⇒ 1 is -4) and
# `¬` is the complement inside the ring (¬-8 is 7).
# • Reduction on entry — `↦ wrapping<i8>` and a constant stored with `←`
# reduce into the ring: 300 becomes 44, and 200 becomes -56.
# • A real port — Java's `String.hashCode` is `h = 31 * h + c` over a signed
# 32-bit word; "hello" hashes to 99162322.
#
# Common mistakes:
# • Expecting a trap on overflow — `wrapping` reduces, it never traps. Only a
# zero divisor fails.
# • Mixing families — `wrapping<i8> + i8` is an error; convert with `↦`.
#
# See also: int, wrapping, ¬, ⇒
# =============================================================================
fn javaHash(list<int> codes) → wrapping<i32> {
mut wrapping<i32> h ← 0
for from codes let c {
let wrapping<i32> code ← c ↦ wrapping<i32>
h ← 31 * h + code
}
return h
}
main {
mut wrapping<i8> a ← 127
a ← a + 1
print a
let wrapping<i8> m ← -128
let wrapping<i8> quotient ← m / -1
print quotient
let wrapping<i8> n ← -7
print n / 2
print n % 2
let wrapping<i8> s ← -8
print s ⇒ 1
print ¬ s
let int wide ← 300
print wide ↦ wrapping<i8>
let int over ← 200
print over ↦ wrapping<i8>
let wrapping<i8> c ← 200
print c
print javaHash([104, 101, 108, 108, 111])
}Expected output:
-128
-128
-4
1
-4
7
44
-56
-56
99162322