我需要在一維封閉場上獲得細胞的鄰居
例如:
鄰居 [1,2,3,4,5,-1](6 個元素)
必須回傳 [[-1,1,2],[1,2,3],[2,3,4],[3,4,5],[4,5,-1],[5,-1 ,1]](6 個元素)
我的鄰居守則
neighbours :: [a] -> [[a]]
neighbours l = concat [[[last l, head l, last $ take 2 l]], neighbours' l, [[l !! (length l - 2), last l, head l]]] where
neighbours' :: [a] -> [[a]]
neighbours' (a:b:c:xs) = [a, b, c]:neighbours (b:c:xs)
neighbours' _ = []
main = print $ neighbours [1, 2, 3, 4]
回傳 [[4,1,2],[1,2,3],[4,2,3],[2,3,4],[4,3,4],[3,4,3], [3,4,2],[3,4,1]](8 個元素),但預期為 [[4,1,2],[1,2,3],[2,3,4],[3 ,4,1]](4 個元素)
如果我評論鄰居的 l 它會按預期回傳 [[4,1,2],[3,4,1]] (2 個元素)
如果你只留下鄰居的 l 它按預期回傳 [[1,2,3],[2,3,4]] (2 個元素)
2 2=4,但在這種情況下由于某種原因它是 8
為什么會發生?
附言
鄰居的創建串列中間
鄰居的 [1,2,3,4,5,-1] == [[1,2,3],[2,3,4],[3,4,5],[4,5,-1 ]]
[last l, head l, last $ take 2 l] 創建串列頭 [-1,1,2]
[我!!(length l - 2), last l, head l] 創建串列的最后一個元素 [5,-1,1]
uj5u.com熱心網友回復:
您的代碼有點難以掌握,因為您的兩個函式neighbour和neighbour'是相互遞回的,這有點不尋常。
您的代碼中的關鍵行是:
neighbours' (a:b:c:xs) = [a, b, c] : neighbours (b:c:xs)
如果我們假設這不是故意的,而您只是想寫:
neighbours' (a:b:c:xs) = [a, b, c] : neighbours' (b:c:xs)
----------------------------------------------- ---------
然后代碼按您的預期作業。
請注意,具有長(超過 80 個字符)的代碼行會使除錯變得非常困難。
建議代碼:
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ExplicitForAll #-}
import qualified Data.List as L
neighbours :: [a] -> [[a]]
neighbours l = concat [
[[last l, head l, last $ take 2 l]],
neighbours' l,
[[l !! (length l - 2), last l, head l]]
]
where
neighbours' :: [a] -> [[a]]
neighbours' (a:b:c:xs) = [a, b, c] : neighbours' (b:c:xs)
neighbours' _ = []
-- neighbour is British English, neighbor is US English
neighbors :: [a] -> [[a]]
neighbors xs =
take count $ drop (count-1) allTriplets -- section of infinite list
where
count = length xs
allTriplets = map (take 3) (L.tails (cycle xs)) -- raw material
main :: IO ()
main = do
print $ "res1 = " (show $ neighbours [1, 2, 3, 4])
print $ "res2 = " (show $ neighbors [1, 2, 3, 4])
程式輸出:
"res1 = [[4,1,2],[1,2,3],[2,3,4],[3,4,1]]"
"res2 = [[4,1,2],[1,2,3],[2,3,4],[3,4,1]]"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445999.html
標籤:哈斯克尔
