3

我想让对象根据它们的类型与特定的交互进行交互。

示例问题:我有四个粒子,两个是A型,两个是B型。当A型交互时我想使用该功能

function interaction(parm1, parm2)
    return parm1 + parm2
end

当 B 型交互时我想使用该功能

function interaction(parm1, parm2)
        return parm1 * parm2
    end

当 A 型与 BI 型交互时要使用函数

function interaction(parm1, parm2)
        return parm1 - parm2
    end

这些功能故意过于简单。

我想计算一个依赖于成对交互的简单总和:

struct part
    parm::Float64
end

# part I need help with:
# initialize a list of length 4, where the entries are `struct part`, and the abstract types
# are `typeA` for the first two and `typeB` for the second two. The values for the parm can be
# -1.0,3, 4, 1.5 respectively

energy = 0.0
for i in range(length(particles)-1)
    for j = i+1:length(particles)
        energy += interaction(particles[i].parm, particles[j].parm)
    end
end

println(energy)

假设使用参数particle[1].parm = -1, particle[2].parm = 3, particle[3].parm = 4, particle[4].parm = 1.5, 能量应该解释

(1,2) = -1 + 3 = 2
(1,3) = -1 - 4 = -5
(1,4) = -1 - 1.5 = -2.5
(2,3) = 3 - 4 = -1
(2,4) = 3 - 1.5 = 1.5
(3,4) = 4 * 1.5 = 6

energy = 1

这样做if statements几乎是微不足道的,但不可扩展。我追求干净、整洁的 Julia 方法......

4

2 回答 2

4

你可以这样做(我使用最简单的实现形式,因为在这种情况下就足够了,而且我希望会发生什么是明确的):

struct A
    parm::Float64
end

struct B
    parm::Float64
end

interaction(p1::A, p2::A) = p1.parm + p2.parm
interaction(p1::B, p2::B) = p1.parm * p2.parm
interaction(p1::A, p2::B) = p1.parm - p2.parm
interaction(p1::B, p2::A) = p1.parm - p2.parm # I added this rule, but you can leave it out and get MethodError if such case happens

function total_energy(particles)
    energy = 0.0
    for i in 1:length(particles)-1
        for j = i+1:length(particles)
            energy += interaction(particles[i], particles[j])
        end
    end
    return energy
end

particles = Union{A, B}[A(-1), A(3), B(4), B(1.5)] # Union makes sure things are compiled to be fast

total_energy(particles)
于 2020-08-07T07:32:34.487 回答
-3

我不知道如何用你的语言做到这一点,但你需要的是类似于我们在面向对象编程中所说的策略模式。策略是一种可插入、可重用的算法。在Java中,我会制作一个像这样的接口:

interface Interaction<A, B>
{
    double interact(A a, B b)
}

然后执行此操作 3 次,并在需要交互的任何地方重用这些部分。另一种方法可以在不知道如何实现的情况下进行交互并使用它。我想这就是你想要的效果。对不起,我不知道如何翻译成你的方言。

于 2020-08-07T02:16:49.910 回答