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 |
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 |
|||
val::Int8 |
|||
function |
function LittleInt(n::Real) |
||
1 ≤ n ≤ 10 || throw(ArgumentError("LittleInt number must be in [1, 10]")) |
|||
this = new() |
|||
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 |
|||
⚫ | |||
convert(U10, x) = U10(x) |
|||
⚫ | |||
Int(x::U10) = x.Ulessthan11 |
|||
# Convenient macro for defining multiple operators at once, see Julia documentation examples. |
|||
⚫ | |||
⚫ | |||
@eval (Base.$op)(a::U10,b) = (Base.$op)(a.Ulessthan11, b) |
|||
end |
end |
||
# Test |
|||
# Testing... |
|||
a = |
a = LittleInt(3) |
||
b = |
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: |
|||
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}}== |