Define a primitive data type: Difference between revisions

m
m (Undo revision 256224 by Wherrera (talk))
Line 934:
<lang julia>
mutable struct U10
Ulessthan11::UInt8Int
function U10(x = 0)
this = new()
x = Int(x)
if x < 0 || x > 10
Base.throw("InexactError: U10 out of bounds, must be >= 0, <= 10")
end
this.Ulessthan11 = UInt8(x)
this
end
end
 
convert(U10, x) = U10(x)
Int(x::U10) = x.Ulessthan11
 
# Convenient macro for defining multiple operators at once, see Julia documentation examples.
for op = (:+, :*, :/, :-, :&, :|, :$, :<, :>, :(==))
@eval (Base.$op)(a::U10,b::U10) = U10((Base.$op)(a.Ulessthan11, b.Ulessthan11))
@eval (Base.$op)(a::U10,b) = U10((Base.$op)(a.Ulessthan11, b))
end
 
# Testing...
a = U10(3)
b = U10(4.0)
println(arrtypeof(a))
c = 1
d = 3.5
f = U10(2)
g = U10(7)
h = U10()
 
foo(x::U10,y::U10) = U10(x + x + y)
gi = U10foo(7a,b)
typeof(i)
 
arr = [ 1, f, a, b, 5]
arr[1] = a * f * h
println("arr[1] is now type $(typeof(arr[1]))")
arr[3] = 0
println("arr[3] is now type $(typeof(arr[3]))")
 
println(arr)
println("$a + $b = $(a+b)")
println("$b * c$f = $(b*cf)\n")
 
println("a * b is 12. so should get bounds error below:")
# no error, below, since arr[1] is quietly promoted to an Int:
# A bounds error here since a*b would overflow as 12:
arr[1] = b * a
println(arr)
 
# But a bounds error before printing here:
arr[4] = U10(b * a)
println(arr)
</lang>
 
4,108

edits