Define a primitive data type: Difference between revisions
Content added Content deleted
Line 929: | Line 929: | ||
add( s(1); s(2)) | pp # "smallint::3" |
add( s(1); s(2)) | pp # "smallint::3" |
||
add( s(6); s(6)) # (nothing)</lang> |
add( s(6); s(6)) # (nothing)</lang> |
||
=={{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: |
|||
<lang julia> |
|||
mutable struct U10 |
|||
Ulessthan11::UInt8 |
|||
function U10(x=0) |
|||
this = new() |
|||
if x < 0 || x > 10 |
|||
Base.throw("InexactError: U10 out of bounds, must be >= 0, <= 10") |
|||
end |
|||
this.Ulessthan11 = UInt8(x) |
|||
end |
|||
end |
|||
convert(U10, x) = U10(x) |
|||
a = U10(3) |
|||
b = U10(4.0) |
|||
c = 1 |
|||
d = 3.5 |
|||
f = U10(2) |
|||
g = U10(7) |
|||
h = U10() |
|||
arr = [ 1, f, a, b, 5] |
|||
arr[1] = a * f * h |
|||
arr[3] = 0 |
|||
println(arr) |
|||
println("$a + $b = $(a+b)") |
|||
println("b * c = $(b*c)\n") |
|||
# no error, below, since arr[1] is quietly promoted to an Int: |
|||
arr[1] = b * a |
|||
println(arr) |
|||
# But a bounds error before printing here: |
|||
arr[4] = U10(b * a) |
|||
println(arr) |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |