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

查看:128
本文介绍了在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声明.但是我随后将如何实现对Myint8中的位进行操作的函数myplus?

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,我问的原因不是因为我需要做朱莉娅特有的事情;我正在设计自己的语言很有趣,并且正在研究其他语言如何实现各种功能.

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.

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天全站免登陆