-3
我有以下代碼。我想知道是否有任何方法可以優化,以便運行得更快。Haskell:這個代碼可以優化嗎?
我想用SegmentTree
來解決它,但我對Haskell並不熟悉,這就是爲什麼我採用以下列表(非樹)方法。
-- Program execution begins here
main :: IO()
main = do
_ <- getLine
arr <- map (read :: String -> Integer) . words <$> getLine
queryList <- readData
let queries = map (read :: String -> Integer) queryList
putStrLn ""
mapM_ print $ compute queries arr
-- Construct a sublist
sublist :: Integer -> Integer -> [Integer] -> [Integer]
sublist start end list = take (fromInteger end - fromInteger start) . drop (fromInteger start) $ list
-- Calculate the resulting list
compute :: [Integer] -> [Integer] -> [Integer]
compute [_] [_] = []
compute [_] [] = []
compute [_] (_:_) = []
compute [] (_:_) = []
compute [] [] = []
compute (x1:x2:xs) list = result : compute xs list where
result = frequency $ sublist x1 x2 list
-- Read query list, end at terminating condition
readData :: IO [String]
readData = do
x <- getLine
if x == "0"
then return []
else do xs <- readData
return (words x ++ xs)
-- Return count of the most frequent element in a list
frequency :: [Integer] -> Integer
frequency list = toInteger (snd $ maximumBy (compare `on` snd) counts) where
counts = nub [(element, count) | element <- list, let count = length (filter (element ==) list)]
謝謝。
你能用代碼解釋嗎?謝謝 –
@ZubinKadva你可以說服我花點時間試着弄清楚(也許你不知道的谷歌搜索條件),然後製作一個問題來確定你在那個過程中遇到困難。您可能還喜歡古老的[如何以智能方式提出問題](http://www.catb.org/~esr/faqs/smart-questions.html),特別是[如果您不明白...] (http://www.catb.org/~esr/faqs/smart-questions.html#lesser)和[明確提出您的問題](http://www.catb.org/~esr/faqs/smart- questions.html#明確)。 –