我有以下玩具程序循环移动一个向量并将其添加到自己(在mod下)。它为不同的移位和大量的迭代(与向量的大小相比)。节目作品,但它的狗慢。我还在学习哈斯克尔,所以我的问题是:我做错了什么?
import Data.List (foldl')
import qualified Data.Sequence as Seq
import Data.Sequence (index, zipWith, Seq, (>))
seqSize = 100
numShifts = 10000
cycleShift :: Integer -> Seq a -> Seq a
cycleShift s l = Seq.drop (fromInteger s) l >< Seq.take (fromInteger s) l
modAdd :: Seq Integer -> Seq Integer -> Seq Integer
modAdd s t = Seq.zipWith (\ a b -> (a + b) `mod` 10^16) s t
step :: Seq Integer -> Integer -> Seq Integer
step l shift = modAdd l (cycleShift shift l)
allshifts = [i `mod` seqSize |i
start = Seq.fromList (1 : [0 | i
end = foldl' step start allshifts
main :: IO ()
main = print (Seq.index end 0)
Python中的程序相同
seq_size = 100
num_shifts = 10000
S = [i % seq_size for i in xrange(1, num_shifts + 1)]
ssums = [1] + [0 for i in range(seq_size - 1)]
for s in S:
shift = ssums[s:] + ssums[:s]
ssums = [(ssums[i] + shift[i]) % 10**16 for i in range(seq_size)]
print ssums[0]
这是时间。
Haskell:real 0m5.596s
Python:真正的0m0.551s
Python的速度并不知名,但是x10倍快?