簡體   English   中英

可以對此Haskell代碼進行哪些優化?

[英]What optimizations can be made to this Haskell code?

--Returns last N elements in list
lastN :: Int -> [a] -> [a]
lastN n xs = let m = length xs in drop (m-n) xs

--create contiguous array starting from index b within list a
produceContiguous :: [a] -> Int -> [[a]]
produceContiguous [] _ = [[]]  
produceContiguous arr ix = scanl (\acc x -> acc ++ [x]) [arr !! ix] inset
    where inset = lastN (length arr - (ix + 1)) arr

--Find maximum sum of all possible contiguous sub arrays, modulo [n]
--d is dummy data
let d = [1,2,3,10,6,3,1,47,10]
let maxResult = maximum $ map (\s -> maximum s) $ map (\c -> map (\ac -> (sum ac )`mod` (last n)) c ) $ map (\n -> produceContiguous d n ) [0..(length d) -1]

我是Haskell的新手-剛加入幾天。.如果我做錯了明顯的事情,糟糕

您可以通過觀察map sum (produceContiguous dn) (運行時為Ω(m ^ 2),距離為drop nd的長度m-可能為O(m ^ 3)的時間,來改善運行時間,因為您要追加每次迭代的acc結束)可以折疊為scanl (+) 0 (drop nd) (運行時為O(m))。 我還將進行很多其他樣式方面的更改,但這是我能想到的主要算法。

清理所有風格方面的東西,我可能會寫:

import Control.Monad
import Data.List
addMod n x y = (x+y) `mod` n
maxResult n = maximum . (scanl (addMod n) 0 <=< tails)

在ghci中:

*Main> jaggedGoofyMax 100 [1..1000]
99
(12.85 secs, 24,038,973,096 bytes)
*Main> dmwitMax 100 [1..1000]
99
(0.42 secs, 291,977,440 bytes)

這里沒有顯示的jaggedGoofyMax版本僅應用了我在第一段中提到的優化,當在ghci中運行時, dmwitMax運行時/內存使用情況統計更好(但與dmwitMax都使用-O2編譯時基本相同) 。 因此,您可以看到,即使輸入大小適中,此優化也會有很大的不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM