Define a primitive data type: Difference between revisions

Content added Content deleted
mNo edit summary
Line 931: Line 931:


=={{header|Julia}}==
=={{header|Julia}}==
Julia has true, machine-optimized user defined primitives, but they are defined as contiguous groups of N bits. Thus, a user defined primitive in Julia can be a 3-bit unsigned value between 0 and 7 or a 4-bit one from 0 to 15, but 0 to 10 requires extra constraints in the constructor as below:
Julia has true, machine-optimized user defined primitives, but they are defined as contiguous groups of N bits:

<lang julia>
<lang julia>struct LittleInt <: Integer
mutable struct U10
Ulessthan11::Int
val::Int8
function U10(x = 0)
function LittleInt(n::Real)
1 ≤ n ≤ 10 || throw(ArgumentError("LittleInt number must be in [1, 10]"))
this = new()
x = Int(x)
return new(Int8(n))
if x < 0 || x > 10
Base.throw("InexactError: U10 out of bounds, must be >= 0, <= 10")
end
this.Ulessthan11 = x
this
end
end
end
end
Base.show(io::IO, x::LittleInt) = print(io, x.val)
Base.convert(::Type{T}, x::LittleInt) where T<:Number = convert(T, x.val)
Base.promote_rule(::Type{LittleInt}, ::Type{T}) where T<:Number = T


for op in (:+, :*, :÷, :-, :&, :|, :$, :<, :>, :(==))
convert(U10, x) = U10(x)
@eval (Base.$op)(a::LittleInt, b::LittleInt) = LittleInt(($op)(a.val, b.val))
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) = (Base.$op)(a.Ulessthan11, b)
end
end


# Test
# Testing...
a = U10(3)
a = LittleInt(3)
b = U10(4.0)
b = LittleInt(4.0)
@show a b
println(typeof(a))
@show a + b
f = U10(2)
@show b - a
h = U10()
@show a * LittleInt(2)

@show b ÷ LittleInt(2)
foo(x::U10,y::U10) = U10(x + x + y)
@show a * b</lang>
i = foo(a,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("$a + $b = $(a+b)")
println("$b * $f = $(b*f)\n")


{{out}}
println("a * b is 12. So should get bounds error below:")
<pre>a = 3
# A bounds error here since a*b would overflow as 12:
arr[1] = b * a
b = 4
a + b = 7
</lang>
b - a = 1
a * LittleInt(2) = 6
b ÷ LittleInt(2) = 2
ERROR: LoadError: ArgumentError: LittleInt number must be in [1, 10]</pre>


=={{header|Kotlin}}==
=={{header|Kotlin}}==