Julia 中的构造函数:根据其他命名字段的输入值初始化命名字段

Constructors in Julia: initializing named fields based on the input value of other named fields

想象一个接受两个参数并使用这两个参数的值初始化 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

但是 ab 显然直到调用 test1(a,b) 才定义,所以这不起作用。也许我只是在寻找语法糖。无论如何,我想更好地理解构造函数的参数值何时已知以及它们是否可以在调用 new().

之前使用

是否有更好的方法(比第一个示例更好)来完成我在第二个示例中尝试做的事情?

(我认为以下问题及其答案足够相关,可以提供帮助,但我仍然是 Julia 新手Building a non-default constructor in Julia

编辑:冒着过于具体的风险,我想我应该包括出现这个问题的实际用例。我正在做一个自适应集成方案。跨越集成边界的每个体积元素都被进一步细分。我对 "cube" 类型的定义如下。我的学生在 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

内部构造函数只是出现在类型块内部的函数,与类型同名。这意味着您可以使用 function syntax 来定义它们。您可以使用缩写形式(如上所示),也可以改用更详细的块语法:

type test1
   a
   b
   c
   function test1(a,b)
      c = a/b
      return new(a,b,c)
   end
end

new 的调用甚至不需要是方法中的最后一个表达式;您可以将其结果分配给一个中间变量,然后 return 它。


更多细节:type 块与普通 Julia scope 块一样,但有一些例外:

  • 任何单独出现或带有类型注释的符号都成为该类型的字段。
  • 函数可以访问特殊的 new 内置函数来实例化类型,并且与类型同名的函数成为内部构造函数。

当您在类型块中放置任何其他赋值时,它们只是在该范围内创建一个局部变量。它不是一个字段或类型的一部分,而只是一个可以在构造函数的方法中使用的变量。也就是说,它不是很有用,可能 change in the future.

使用 Matt B. 的回答,我为我的特定用例构建了以下答案。对函数使用块语法更简洁。

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 # tuple: List of positions of the vertices 
    fvals # 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)

    function cube(pos,dx,depth,maxdepth)
        verts = [pos+[vt...].*dx for vt in product(0:1,0:1,0:1)]
        fvals = [fVal([vt...]) for vt in verts ]
        return new(pos,dx,verts,fvals,depth,maxdepth)
    end
end