我正在用Haskell做粒子模拟程序。对于其中一个函数,我试图根据所有周围粒子的质量和速度来确定模拟中所有粒子的新速度。
该职能的形式如下:
accelerate :: Float -> [Particle] -> [Particle]粒子是包含质量、位置矢量和速度矢量的数据类型,“浮点”参数表示仿真中各个时间步长的增量时间。
我想要一些关于可能的函数的建议,我可以用来遍历列表,同时计算每个粒子相对于列表中其他粒子的速度。
我能想到的一个可能的方法是:
这需要两个粒子,并返回第一个粒子的更新速度矢量。
我不知道这是否最有效的方法,因此,任何建议和改进都是非常感谢的。
,如我所说,请注意->,我只是在寻找建议,而不是回答!
谢谢!
发布于 2015-04-13 00:26:14
似乎您已经开始使用foldl了。例如
foldl应用于每个元素,并以更新的速度构建包含粒子的新列表。根本没什么意义。根据一些二进制总结函数,可以将foldl应用到列表中,以将其简化为“摘要值”。把它应用到单个粒子上是没有意义的。
我是在回答这个问题,假设你一开始就在编写程序时遇到了困难--通常在担心效率之前最好这样做。如果我想错了,请告诉我。
我不知道你想用什么规则来更新速度,但我想这是一种对力的模拟,例如重力或电磁学。如果是这样的话,这里有一些提示将指导您找到解决方案。
type Vector = (Float, Float)
-- Finds the force exerted on one particle by the other.
-- Your code will be simplified if this returns (0,0) when the two
-- particles are the same.
findForce :: Particle -> Particle -> Vector
-- Find the sum of all forces exerted on the particle
-- by every particle in the list.
totalForce :: [Particle] -> Particle -> Vector
-- Takes a force and a particle to update, returns the same particle with
-- updated velocity.
updateVelocity :: Vector -> Particle -> Particle
-- Calculate mutual forces and update all particles' velocities
updateParticles :: [Particle] -> [Particle]这些功能中的每一个都很短,只有一两行。如果您需要更多的提示来使用更高级的函数,请注意要编写的函数的类型,并注意。
map :: (a -> b) -> [a] -> [b] -- takes a list, returns a list
filter :: (a -> Bool) -> [a] -> [a] -- takes a list, returns a list
foldl :: (a -> b -> a) -> a -> [b] -> a -- takes a list, returns something else
foldr :: (a -> b -> b) -> b -> [a] -> b -- takes a list, returns something elsehttps://stackoverflow.com/questions/29588791
复制相似问题