
生信探索
V1
2023/04/27阅读:16主题:姹紫
Julia编程10:类型系统(Types)
<~生~信~交~流~与~合~作~请~关~注~公~众~号@生信探索>
基于类型系统的多重派发是Julia的核心,但是类型系统也挺复杂的,以下只是我的简单理解。
类型树
-
Any是根类型,所有其他类型都是他的子类,如果函数的参数不指定类型则为Any类型 -
一般不会给函数返回值设置类型,julia可以自动推断返回值类型 -
抽象类型不能示例化,比如Any、AbstractString等 -
Primitive type 是有计算机硬件支持的类型, 比如Float64、Char等;但BigInt等不是primitive type -
只有叶子节点(后边没有分支)上的类型才能被实例化,比如Int64、Int32

有理数
有理数是整数(正整数、0、负整数)和分数的统称
# 分数
typeof(1 // 3) == Rational{Int64}
Float64(1 // 3) ≈ 0.3333333333333333
类型判断
# 判断是不是实例
isconcretetype(Int) # true
eltype([1,2.0,3]) # 元素类型
typeof([1,2.0,3]) # 容器类型
typeof([1,2,1.0]) # Vector{Float64}
# true Int64 是 Any 的子类
Int64 <: Any
1 isa Int # true
isa(1,Int) # true
类型转换
-
数字
round(88.88)==89.0
round(Int,88.88)==89
round(88)==88
convert(Int64,1.0) # 或者 Int64(1.0)
##1
# 字符串转数字
parse(Int64,"88")
##88
# 数字转字符串
string(88)
##"88"
参数化类型
一个容器collection
也有自己的类型,而且可以提前定义好。
[]
#Any[]
Dict()
#Dict{Any, Any}()
Float64[1,2,3]
# 3-element Vector{Float64}:
# 1.0
# 2.0
# 3.0
The isa
function tests if an object is of a given type and returns true or false,
isa 相当于判断一个对象是不是某个类型的实例,抽象类型Real没有办法实例化
Julia中给出了另一种方法,Vector{<:Real}
或者Vector{T} where T<:Real
,这种类型实际上包括了多种类型,Vector{Int64}
、Vector{Float64}
、Vector{Int32}
等等
[1,2,3] isa Vector{Int64}
# true
[1,2,3] isa Vector{Real}
# false
[1,2,3] isa Vector{<:Real}
# true
Vector{Int64} <: Vector{<:Real}
# true

Vector{Int}
和Vector{Real}
是平行关系,代表了两个不同的容器
复合类型Type Unions
IntOrFloat64 = Union{Int,Float}
isconcretetype(IntOrFloat64) # false
Int <:: IntOrFloat64 # true
typejoin(typeof([1.0,2.0,3.0]),typeof(1:3))
#>AbstractVector (alias for AbstractArray{T, 1} where T)
作者介绍

生信探索
V1
微信公众号:生信探索