Define a primitive data type: Difference between revisions
m
→{{header|Julia}}
Line 934:
<lang julia>
mutable struct U10
Ulessthan11::
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)
f = U10(2)
g = U10(7)▼
h = U10()
foo(x::U10,y::U10) = U10(x + x + y)
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 *
println("a * b is 12. so should get bounds error below:")
# A bounds error here since a*b would overflow as 12:
arr[1] = b * a
</lang>
|