Implementing custom primitive types in Julia

Julia's documentation says:

A primitive type is a specific type whose data consists of a simple old bit. The classic examples of primitive types are integers and floating point values. Unlike most languages, Julia allows you to declare your own primitive types, rather than providing only a fixed set of built-in types. In fact, standard primitive types are defined in the language itself:

I cannot find an example of how to do this, although either in the documents, or in the source code, or elsewhere. I am looking for an example of how to declare a primitive type and how to subsequently implement a function or method for this type that works by manipulating these bits.

Can someone give me an example? Thanks.


Edit: It’s clear how to declare a primitive type, as there are examples immediately below the citation in the document. I hope to receive information on how to subsequently manipulate them. For example, let's say I wanted (meaninglessly) to implement my own primitive type MyInt8 . I could declare this with the primitive type MyInt8 <: Signed 8 end . But how could I subsequently implement the myplus function, which controlled the bits inside MyInt8 ?

PS in case this helps, the reason I'm asking for is not that I need to do something specific in Julia; I design my own language for fun, and I learn how other languages ​​implement different things.

+5
source share
1 answer
 # Declare the new type. primitive type MyInt8 <: Signed 8 end # A constructor to create values of the type MyInt8. MyInt8(x :: Int8) = reinterpret(MyInt8, x) # A constructor to convert back. Int8(x :: MyInt8) = reinterpret(Int8, x) # This allows the REPL to show values of type MyInt8. Base.show(io :: IO, x :: MyInt8) = print(io, Int8(x)) # Declare an operator for the new type. import Base: + + (a :: MyInt8, b :: MyInt8) = MyInt8(Int8(a) + Int8(b)) 

The key function here is reinterpret . This allows us to consider the Int8 bit representation as a new type.

To save the value using a custom bitmap inside the constructor of MyInt8, you could perform any of the standard bit manipulation functions in Int8 before re-interpreting them as MyInt8.

+1
source

Source: https://habr.com/ru/post/1273609/


All Articles