我想让对象根据它们的类型与特定的交互进行交互。
示例问题:我有四个粒子,两个是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 方法......