Define a primitive data type: Difference between revisions

Content added Content deleted
m (Undo revision 256224 by Wherrera (talk))
Line 934: Line 934:
<lang julia>
<lang julia>
mutable struct U10
mutable struct U10
Ulessthan11::UInt8
Ulessthan11::Int
function U10(x=0)
function U10(x = 0)
this = new()
this = new()
x = Int(x)
if x < 0 || x > 10
if x < 0 || x > 10
Base.throw("InexactError: U10 out of bounds, must be >= 0, <= 10")
Base.throw("InexactError: U10 out of bounds, must be >= 0, <= 10")
end
end
this.Ulessthan11 = UInt8(x)
this.Ulessthan11 = UInt8(x)
this
end
end
end
end

convert(U10, x) = U10(x)
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)
a = U10(3)
b = U10(4.0)
b = U10(4.0)
println(typeof(a))
c = 1
d = 3.5
f = U10(2)
f = U10(2)
g = U10(7)
h = U10()
h = U10()

foo(x::U10,y::U10) = U10(x + x + y)
i = foo(a,b)
typeof(i)

arr = [ 1, f, a, b, 5]
arr = [ 1, f, a, b, 5]
arr[1] = a * f * h
arr[1] = a * f * h
println("arr[1] is now type $(typeof(arr[1]))")
arr[3] = 0
arr[3] = 0
println("arr[3] is now type $(typeof(arr[3]))")


println(arr)
println("$a + $b = $(a+b)")
println("$a + $b = $(a+b)")
println("b * c = $(b*c)\n")
println("$b * $f = $(b*f)\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
arr[1] = b * a
println(arr)

# But a bounds error before printing here:
arr[4] = U10(b * a)
println(arr)
</lang>
</lang>