京香茱莉亚_深入了解茱莉亚类型

京香茱莉亚

Get to know about some built-in operators, literals and Unions

了解一些内置运算符,文字和并集

This is part 5 of the Julia Tutorials (a series of tutorials on Julia). If you are not familiar with Julia Types, please go through part 4 (Variables and Types in Julia) for better understanding.

这是Julia教程(有关Julia的一系列教程)的第5部分。 如果您不熟悉Julia类型,请阅读第4部分 (Julia中的变量和类型)以更好地理解。

If you are not familiar with Julia and want to get started with it, feel free to check out the complete series @ —

如果您不熟悉Julia,并想开始使用它,请随时查看完整的系列@-

Note: Use Julia’s REPL to quickly follow along with the codes in this tutorial

注意:使用Julia的REPL可以快速遵循本教程中的代码

Okay, as discussed in the previous tutorial let’s get started by demystifying the :: operator. Before going there, let’s get acquainted with a built-in function typeof() , which can be used to obtain type of a value. You can see it’s usage in the below example.

好的,正如上一教程中所讨论的,让我们开始揭密::运算符。 在去那里之前,让我们熟悉一个内置函数typeof() ,该函数可用于获取值的类型。 您可以在以下示例中查看其用法。

:: has different functionalities in different contexts, let’s see what they are:

::在不同的上下文中具有不同的功能,让我们看看它们是什么:

声明(子)类型 (Declaring a (sub)type)

In the context of a statement, such as a function, :: can be used to restrict the type of a variable.

语句 (例如函数)的上下文中, ::可以用于限制变量的类型。

Example:

例:

# Declare the function
function restrict_this_integer()
x::Int8 = 32
x
end
# Call the function
p = restrict_this_integer()
typeof(p) # Output will be Int8

Note: Don’t worry about the function definition, it will be discussed in a follow up tutorial.

注意 :不用担心函数定义,它将在后续教程中进行讨论。

断言类型 (Asserting a type)

In every other context, :: means 'I assert this value is of this particular type'. This is a great way to check a value for both abstract and concrete type.

在所有其他上下文中, ::表示“我断言该值为该特定类型”。 这是检查抽象和具体类型的值的好方法。

Example:

例:

integer_value = 10# Assert integer_value if of type Int64
integer_value::Int64# Assert integer_value if of type Char
integer_value::Char

The assertion for Int64 will return the value stored in “integer_value” and the assertion for Char will result in a TypeError — ERROR: TypeError: in typeassert, expected Char, got Int64 .

Int64的断言将返回存储在“ integer_value”中的值,而Char的断言将导致TypeError — ERROR: TypeError: in typeassert, expected Char, got Int64

指定可接受的功能输入 (Specifying acceptable function inputs)

While we haven’t really discussed function inputs, you should be familiar with the general idea of ​​a function — mapping a tuple of arguments using some expression to a return value. Julia can ensure that a function only accepts values ​​that we want.

虽然我们还没有真正讨论过函数输入,但您应该熟悉函数的一般概念-使用某些表达式将参数元组映射到返回值。 Julia可以确保函数仅接受我们想要的值。

Let’s define a function which takes 2 integers as input and provides their sum as output.

让我们定义一个函数,该函数接受2个整数作为输入并提供它们的总和作为输出。

function add(x::Int64, y::Int64)
x + y
end
# Call the function on 2 integers
result = add(16, 14)Outputs -> 30
# Call the function on 2 floats
result = add(2.0, 3.5)Outputs -> ERROR: MethodError: no method matching add(::Float64, ::Float64)

As you can see from the above examples, any types other than the specified one ( Int64 ) results in an error.

从上面的示例中可以看到,除指定的类型( Int64 )之外的任何其他类型都会导致错误。

文字 (Literals)

Literals are means of expressing specific values in a program.

文字是在程序中表达特定值的手段。

StringsWe’ve already came across the string literals in some examples, String literals can be created by enclosing the value between " (double quotes).

字符串在某些示例中,我们已经遇到过字符串文字,可以通过将值括在" (双引号)之间来创建字符串文字。

string_val = "test string"

Note: In Julia, strings can only be defined between " (double quote), while '(single quote) is used for defining a character.

注意:在Julia中,只能在" (双引号)之间定义字符串,而' (单引号)用于定义字符。

char_val = 'a'

Arrays/ListsArray literals are N-dimensional mutable containers.

数组/列表数组文字是N维可变容器。

  • Each element they contain has to be either a variable or otherwise a valid literal.

    它们包含的每个元素必须是变量或其他有效文字。
  • Can be heterogeneous, i.e, values don’t have to be of same type.

    可以是异构的,即值不必是同一类型。
  • Values are separated by a , (comma)

    值由一个分开, (逗号)

  • Values can be updated by subscripting through their index.

    可以通过在其索引下标来更新值。

Note: Compared to other programming languages, Julia uses 1 indexing rather than 0 indexing, i.e, indexes start at 1 instead of 0.

注意与其他编程语言相比,Julia使用1索引而不是0索引,即索引从1而不是0开始。

1-D arrays — A linear array which has only one subscript,

一维数组 -线性数组,只有一个下标,

# Initialize an array with values
arr1 = # Initialize an empty array
arr2 = []# Update value by index
arr1[1] = 3 # Updates 1st element of arr1

Multidimensional arrays — A rectangular array of numbers or symbols arranged in rows and columns, also known as matrix. A matrix can be declared in 2 ways,

多维数组 —按行和列排列的数字或符号的矩形数组,也称为矩阵。 矩阵可以通过两种方式声明:

mat1 = [[1,2,3] [4,5,6] [7,8,9]]--or--mat2 = [1 2 3; 4 5 6; 7 8 9]# Update 2nd column in 1st row
mat1[1][2] = 5

While creating a multidimensional array, each row has to be of the same length, otherwise, it raises an error.

创建多维数组时,每行必须具有相同的长度,否则会产生错误。

Elements of bidimensional arrays can be accessed with the array[row,col] or array[row][col] syntax.

可以使用array[row,col]array[row][col]语法访问二维数组的元素。

Nested arrays — Simply speaking, these are an array of arrays, i.e, a 1-D array with vector values.

嵌套数组 —简单来说,它们是数组的数组,即具有矢量值的一维数组。

arr2 = [[1,2,3], [4,5,6], [7,8,9]]

This creates a 1-D array with 3 elements (each of which are vectors). Note the , separation between each vector elements.

这将创建一个具有3个元素(每个元素都是矢量)的一维数组。 请注意,每个向量元素之间的分隔。

TuplesTuples are similar to 1-D arrays, but unlike them, tuples are immutable.

组类似于一维数组,但是与它们不同,元组是不可变的。

tuple1 = (1, 4, 5.5, "test")

NamedTuplesNamedTuples are collections of items whose position in the collection (index) can be identified not only by the position but also by name.

NamedTuples NamedTuples是项目的集合,其在集合(索引)中的位置不仅可以通过位置来标识,还可以通过名称来标识。

namedtuple1 = (a=1, b=2, c=3)# Accessing elements by name
namdetuple1.a
namedtuple1.c

DictionariesDictionaries are used to store key-value pairs.

字典字典用于存储键值对。

# Initialize a dictionary with values
dict1 = Dict('a'=>1, 'b'=>2, 'c'=>3)# Initialize an empty dictionary
dict2 = Dict()# Add new pairs to dictionary
dict1['d'] = 4
dict2['e'] = 5# Update existing pairs
dict['a'] = 8

They may seem similar to NamedTuples but both have some major differences,

它们看起来类似于NamedTuples,但是两者都有一些主要差异,

  • Dictionaries are mutable while NamedTuples are immutable

    字典是可变的,而NamedTuples是不可变的

  • Dictionaries are type unstable if different type of values are stored, while NamedTuples remain type-stable

    如果存储了不同类型的值,则字典类型不稳定,而NamedTuples保持类型稳定
d = Dict(k1=>"v1", k2=>2)  # Dict{Symbol,Any}
nt = (k1="v1", k2=2,) # NamedTuple{(:k1, :k2),Tuple{String,Int64}}

SetsSets are unordered collections used to store unique values.

集集是用于存储唯一值的无序集合。

# Create an empty set
set1 = Set([])# Create a set with values
set2 = Set([1, 2, 3])

Though duplicate entries are present at the time of set construction, the resulting set will only have unique values

尽管在构建集时存在重复的条目,但结果集将仅具有唯一值

set3 = Set(["abcd", "efg", "efg", "hijk"])Output -> Set(["hijk", "efg", "abcd"])

RangesA range in Julia is simply a shorthand for a sequence of numbers that are all spaced equally.

范围 Julia中的范围只是一系列均等间隔的数字的简写。

Syntax:

句法:

range(start:[step]:end)
  • start — denotes the start value of the range

    start —表示范围的起始值

  • step — is optional, specifies the spacing between each values in the sequence

    step —是可选的,指定序列中每个值之间的间隔

  • end — denotes the end value of the range

    end —表示范围的最终值

Ranges are lazy, meaning the values are not immediately available until they are needed. However, the generation of the values can be forced by using the collect() function.

范围是惰性的 ,这意味着这些值直到需要时才立即可用。 但是,可以使用collect()函数强制生成值。

0:20    # This return collect(0:2:20)    # This will generate a 6-element Array{Int64,1}collect(0.5:5.5)   # This will generate a 6-element Array{Float64,1}

类型联合 (Type Unions)

Sometimes, it’s useful to have a single alias for multiple types. To do so, we can create a type union using the constructor Union:

有时,为多个类型使用一个别名很有用。 为此,我们可以使用构造函数Union创建一个类型并集

Numeric = Union{Int, Float64}# Assert for Int
5::Numeric # Returns 5
# Assert for Float
7.06::Numeric # Returns 7.06
# Assert for string
"abcd"::Numeric # Results in TypeError

As you can see from the above example, since String type is not in the Uninon Numeric , asserting for a string will raise TypeError.

从上面的示例中可以看到,由于String类型不在Uninon Numeric ,因此对字符串进行断言将引发TypeError。

Next Up — Operators in Julia

下一步—Julia中的运算符

翻译自: https://medium.com/swlh/dive-deep-into-julia-types-251d51f01c0

京香茱莉亚

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值