在 Julia 中实现自定义原始类型 [英] Implementing custom primitive types in Julia

查看:16
本文介绍了在 Julia 中实现自定义原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Julia 文档说:

原始类型是一种具体类型,其数据由普通旧的位.原始类型的经典示例是整数和浮点值.与大多数语言不同,Julia 允许您声明您自己的原始类型,而不是只提供一组固定的内置的.其实标准的原始类型都是定义的语言本身:

A primitive type is a concrete type whose data consists of plain old bits. Classic examples of primitive types are integers and floating-point values. Unlike most languages, Julia lets you declare your own primitive types, rather than providing only a fixed set of built-in ones. In fact, the standard primitive types are all defined in the language itself:

但是,我无法在文档、源代码或其他任何地方找到如何执行此操作的示例.我正在寻找的是如何声明原始类型的示例,以及如何随后在该类型上实现通过操作这些位来工作的函数或方法.

I'm unable to find an example of how to do this, though, either in the docs or in the source code or anywhere else. What I'm looking for is an example of how to declare a primitive type, and how to subsequently implement a function or method on that type that works by manipulating those bits.

有人能指出我的例子吗?谢谢.

Is anyone able to point me towards an example? Thanks.

如何声明原始类型很清楚,因为文档中的上述引用正下方有示例.我希望获得有关如何随后操纵它们的信息.例如,假设我想(毫无意义地)实现我自己的原始类型 MyInt8.我可以用 primitive type MyInt8 <: Signed 8 end 声明这一点.但是我如何随后实现一个函数 myplus 来操纵 Myint8 中的位?

It's clear how to declare a primitive type, as there are examples immediately below the above quote in the doc. I'm hoping for information about how to subsequently manipulate them. For example, say I wanted to (pointlessly) implement my own primitive type MyInt8. I could declare that with primitive type MyInt8 <: Signed 8 end. But how would I subsequently implement a function myplus that manipulated the bits within Myint8?

PS 如果有帮助,我问的原因不是因为我需要在 Julia 中做任何特定的事情;我设计自己的语言是为了好玩,并且正在研究其他语言如何实现各种功能.

PS in case it helps, the reason I'm asking is not because I need to do anything specific in Julia; I'm designing my own language for fun, and am researching how other languages implement various things.

推荐答案

# 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))

这里的关键功能是reinterpret.它允许将 Int8 的位表示视为新类型.

The key function here is reinterpret. It allows the bit representation of an Int8 to be treated as the new type.

要使用自定义位布局存储值,在 MyInt8 构造函数中,您可以在将 Int8 '重新解释'为 MyInt8 之前对 Int8 执行任何标准位操作函数.

To store a value with a custom bit layout, inside the MyInt8 constructor, you could perform any of the standard bit manipulation functions on the Int8 before 'reinterpreting' them as a MyInt8.

这篇关于在 Julia 中实现自定义原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆