我在玩 Haskell,想知道这两个函数之间的性能是否有任何差异:
count :: (Eq a) => [a] -> a -> Int
count xs e = foldr countCheck 0 xs
where countCheck x
| x == e = (1+)
| otherwise = (0+)
count' :: (Eq a) => [a] -> a -> Int
count' xs e = foldr countCheck 0 xs
where countCheck x acc
| x == e = acc + 1
| otherwise = acc
我尝试使用以下代码作为基准:main = print (count [1..10000] 1)
,这导致第一个(使用部分应用的+
)函数平均稍微快一些。
我主要想知道,因为对我来说,count
阅读起来比count'
. 除了“聪明”之外,我认为另一个权衡必须是它更快。那么使用部分应用的函数会使代码运行得更快吗?如果是这样,为什么?