Optimizing Haskell code

前端 未结 6 1252
轮回少年
轮回少年 2020-12-31 04:20

I\'m trying to learn Haskell and after an article in reddit about Markov text chains, I decided to implement Markov text generation first in Python and now in Haskell. Howev

6条回答
  •  佛祖请我去吃肉
    2020-12-31 05:07

    Here's a foldl'-based version that seems to be about twice as fast as your train:

    train' :: [B.ByteString] -> Database
    train' xs = foldl' (flip f) M.empty $ zip3 xs (tail xs) (tail $ tail xs)
      where
        f (a, b, c) = M.insertWith (M.unionWith (+)) (a, b) (M.singleton c 1)
    

    I tried it on the Project Gutenberg Huckleberry Finn (which I assume is your 76.txt), and it produces the same output as your function. My timing comparison was very unscientific, but this approach is probably worth a look.

提交回复
热议问题