【发布时间】:2015-05-29 14:38:36
【问题描述】:
想象一个构造函数,它接受两个参数并使用两个参数的值初始化 3 个命名字段。像这样的:
type test1
a
b
c
test1(a,b) = new(a,b,a/b)
end
这很好用,但是如果 c 的值不是这么简单的表达式怎么办?如果它超过一两行怎么办?或者是一个复杂的列表理解?将c 的表达式直接粘贴到new() 中很笨拙,并且使代码更难阅读(IMO)。我宁愿做这样的事情:
type test1
a
b
c = a/b
test1(a,b) = new(a,b,c)
end
但是 a 和 b 显然是在调用 test1(a,b) 之前定义的,所以这不起作用。也许我只是在寻找语法糖。无论如何,我想更好地理解构造函数的参数值何时已知以及是否可以在调用new().之前使用它们。
有没有更好的方法(比第一个示例更好)来做我在第二个示例中尝试做的事情?
(我认为以下问题及其答案的相关性足以提供帮助,但我仍然是 Julia 新手Building a non-default constructor in Julia)
已编辑:冒着过于具体的风险,我想我会包括出现这个问题的实际用例。我正在做一个自适应集成方案。跨越积分边界的每个体积元素都被进一步细分。我对“立方体”类型的定义如下。我的学生在 python 中编写了一个工作原型,但我试图在 julia 中重写它以提高性能。
using Iterators
# Composite type defining a cube element of the integration domain
type cube
pos # floats: Position of the cube in the integration domain
dx # float: Edge length of the cube
verts # float: List of positions of the vertices
fvals::Dict # tuples,floats: Function values at the corners of the cube and its children
depth::Int # int: Number of splittings to get to this level of cube
maxdepth::Int # Deepest level of splitting (stopping condition)
intVal # float: this cube's contribution to the integral
intVal = 0
cube(pos,dx,depth,maxdepth) = new(pos,dx,
[i for i in product(0:dx:dx,0:dx:dx,0:dx:dx)],
[vt=>fVal([vt...]) for vt in [i for i in product(0:dx:dx,0:dx:dx,0:dx:dx)]],
depth,maxdepth,intVal)
end
【问题讨论】:
标签: constructor julia composite-types