gpt4 book ai didi

types - 前向类型声明

转载 作者:行者123 更新时间:2023-12-02 00:37:06 24 4
gpt4 key购买 nike

我想知道在 julia 中是否可以将自定义或现有类型分配给变量而不调用它的构造函数。

类似于 C++ 中类的前向声明。

这是我想要实现的目标的示例:

type foo
a
end

#custom type
a = foo
b = foo

#julia type, force c to be of type Int
c = Int


a.a = 5.5
b.a = 4.5

c = 6

编辑澄清我的问题:

在 C++ 或 Fortran 中,在某个时刻声明变量以供以后使用是常见的编码实践。

我不记得正确的 Fortran 语法,但在 C++ 中你会写如下内容:

class foo;
class bar;
int a;

class foo{
private:
bar myBar;

public:
foo(int a){ myBar( a ); }
}

class bar{
public:
bar(int a){
std::cout << a << std::endl;
}
}

a = 3;
foo( a );

这种代码结构的优点是它允许您在使用对象/类型/变量之前定义它们。

最佳答案

您可以声明变量,但不能全局范围中声明;这些是 Julia 中引入新 scope 的构造。 :

Certain constructs in the language introduce scope blocks, which are regions of code that are eligible to be the scope of some set of variables. The scope of a variable cannot be an arbitrary set of source lines; instead, it will always line up with one of these blocks. The constructs introducing such blocks are:

  • function bodies (either syntax)
  • while loops
  • for loops
  • try blocks
  • catch blocks
  • finally blocks
  • let blocks
  • type blocks.

Notably missing from this list are begin blocks and if blocks, which do not introduce new scope blocks.

您可以选择使用type declarations :

julia> x
ERROR: UndefVarError: x not defined

julia> x::Int
ERROR: UndefVarError: x not defined

julia> begin x end # still in global scope
ERROR: UndefVarError: x not defined

julia> begin x::Int end
ERROR: UndefVarError: x not defined

julia> let x end # local scope

julia> let x; x end
ERROR: UndefVarError: x not defined

请注意,Julia 会尝试将值转换为指定类型:

julia> let 
x::Int # declare variables
y::Float64 = 7 # converts (if possible)

x = y # converts (if possible)
x, y
end
(7, 7.0)

julia> function foo(x, y)
x::Int
y::Float64
z # Any

# there must be assignment for conversion to happen
x, y = x, y

z = 5im
x, y, z
end
foo (generic function with 1 method)

julia> foo(3.0, 7)
(3,7.0,0 + 5im)

编辑示例:

定义类型/不可变。

julia> type Foo{T<:Number}
x::T
end

julia> type Bar
x
end

julia> immutable Baz
a
b
c
end

定义转换方法。

julia> import Base.convert

julia> convert{T<:Number}(::Type{Foo{T}}, x::Number) = Foo(T(x))
convert (generic function with 535 methods)

julia> convert(::Type{Bar}, x) = Bar(x)
convert (generic function with 536 methods)

julia> convert(::Type{Baz}, xs::NTuple{3}) = Baz(xs...)
convert (generic function with 537 methods)

所以你可以这样做:

julia> let
# decalre variables:
a::Foo{Int}
b::Foo{Float64}
c::Bar
d::Baz
e::Int

# assign values:
e = 42
a = e
b = e
c = string(e)
d = 'a', e, "test"

[a, b, c, d]
end
4-element Array{Any,1}:
Foo{Int64}(42)
Foo{Float64}(42.0)
Bar("42")
Baz('a',42,"test")

julia>

关于types - 前向类型声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32882253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com