有没有可能加速(或者在我的函数中,删除) Haskell中的相等性检查?我有一个函数,它对一个代理的所有交互进行求和,其中交互是在两个代理之间进行的。为了对交互进行求和,它首先必须检查智能体是否等于交互中的第一个或第二个智能体,然后对其求和。检查相等性几乎占据了我程序运行时间的一半。
sumAgent :: [Interaction] -> Agent -> Int
sumAgent xs agent = foldr (\x acc -> acc + sumInteraction agent x) 0 xs
-- Use this in a map call of sumAgent to return the sums of a specific agent
sumInteraction :: Agent -> Interaction -> Int
sumInteraction agent (Interaction a1 a2 xs )
| (==) agent a1 = sum $ map fst scores
| (==) agent a2 = sum $ map snd scores
| otherwise = 0
where scores = map score xs
是否可以通过使用c函数或只检查部分代理的相等性来删除相等性检查,或者加快相等性检查的速度?Eq实现是:
data Agent = Agent {
function::[(Bool,Bool)] -> Bool,
name::String,
position::(Int,Int),
dna::DNA
}
instance Eq Agent where
(==) a1 a2 = position a1 == position a2
发布于 2013-04-07 11:36:44
你怎么知道平等需要一半的时间?我猜你最有可能通过使用严格的和未装箱的对获得性能上的好处:
data Pair = P {-# UNPACK #-} !Int {-# UNPACK #-} !Int
data Agent = Agent {
function::[(Bool,Bool)] -> Bool,
name::String,
position:: {-# UNPACK #-} !Pair Int Int,
dna::DNA
}
这样,您将避免额外的间接性,并可能获得更好的缓存行为。
https://stackoverflow.com/questions/15858043
复制相似问题