Julia 中的构造函数 : initializing named fields based on the input value of other named fields

标签 constructor julia composite-types

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

编辑:冒着过于具体的风险,我想我应该包括出现这个问题的实际用例。我正在做一个自适应集成方案。跨越集成边界的每个体积元素都被进一步分割。我对“立方体”类型的定义如下。我的学生用 Python 编写了一个工作原型(prototype),但我正在尝试用 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

最佳答案

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

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

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


更多细节:type block 就像一个普通的 Julia scope除了少数异常(exception):

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

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

关于Julia 中的构造函数 : initializing named fields based on the input value of other named fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532423/

相关文章:

java - 类的ArrayList作为参数

c++ - 如何在派生类中创建与基类同名的函数

c++ - 构造函数右括号处的无法访问的代码

python - Julia (v1.3.1) 中是否存在 `logspace` 的任何替代方案?

multithreading - 线性系统求解器在 Julia 中是否也像在 Matlab 中一样是多线程的?以及如何在 Julia 中对其进行 "multithread"处理?

c# - C# Npgsql 传递的复合类型数组作为存储过程输入

java - 如何使用 JDBC 在 PostgreSQL 中传递一组复合类型 (UDT)

javascript - 如何在 Javascript 构造函数中添加和调用函数(使用 JQuery)

node.js - 在cassandra中选择compositetype键

multiprocessing - Julia 等价于 Python multiprocessing.Pool.map