加速检查Haskell中的平等性

时间:2013-04-07 01:51:07

标签: haskell optimization profiling

是否有可能加速(或在我的函数中删除)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

1 个答案:

答案 0 :(得分:2)

你怎么知道平等需要一半的时间?我猜你最有可能通过使用严格和未装箱的对来获得性能优势:

 data Pair = P {-# UNPACK #-} !Int {-# UNPACK #-} !Int
 data Agent = Agent {
            function::[(Bool,Bool)] -> Bool,
            name::String,
            position:: {-# UNPACK #-} !Pair Int Int,
            dna::DNA
           }

这样你就可以避免额外的间接,并可能获得更好的缓存行为。