下面介紹的解決方案如何改進以下問題?它能在時間和空間上更有效率嗎?是否有空間泄漏?如何改進Haskell組合算法?
問題: 鑑於Astronauts
輸入列表中,產生對Astronauts
這樣的,該對不具有來自相同國家二級Astronauts
的列表。假設輸入具有Astronauts
的列表以及唯一的identifier
s。
data Astronaut = Astronaut { identifier :: Int, country :: String } deriving (Eq)
astronautPairs :: [Astronaut] -> [(Astronaut, Astronaut)]
astronautPairs xs = foldl accumulatePairs [] [(a, b) | a <- xs, b <- xs, country a /= country b]
where
accumulatePairs pairs pair = if hasPair pair pairs then pairs else pair:pairs
hasPair [email protected](a,b) ((c,d):xs) = a == d && b == c || hasPair pair xs
hasPair _ [] = False
您認爲應該佔用多少空間?一旦你決定,只需在一個大輸入上運行你的代碼,看看你的內存使用情況是否匹配(在這裏'-stderr'運行時選項可以派上用場)。然後你告訴我們*是否有空間泄漏。 – crockeea
您可能喜歡[我之前的答案](http://stackoverflow.com/a/6473153/791604)中的'pairs'函數。 –
你想同時生產'(a,b)'和'(b,a)',還是你打算代表兩人團隊? – dfeuer