[英]What can be the problem with my haskell code and how can I fix it?
deadNeighbors:給出在該代中具有活細胞鄰居的空細胞列表。 確保每個單元格只列出一次!
有些東西對我的 deadNeighbors function 不起作用,但我不知道它有什么問題。 有人可以幫我修復 deadNeighbors 嗎?
type Coordinate = (Integer, Integer)
type Generation = [Coordinate]
single :: Generation
single = [ (42, 42) ]
row :: Generation
row = [ (10, 1), (10, 2), (10, 3) ]
代碼:
neighbors :: Coordinate -> [Coordinate]
neighbors (x,y) = [(x-1,y-1), (x-1,y), (x-1,y+1), (x ,y-1), (x,y+1), (x+1,y-1), (x+1,y), (x+1,y+1)]
alive :: Generation -> Coordinate -> Bool
alive x y = elem y x
livingNeighbors :: Generation -> Coordinate -> Int
livingNeighbors a = length .filter (alive a) . neighbors
staysAlive :: Generation -> Coordinate -> Bool
staysAlive a b
| alive a b = livingNeighbors a b `elem` [2,3]
| otherwise = livingNeighbors a b `elem` [3]
問題:
deadNeighbors :: Generation -> [Coordinate]
deadNeighbors (neighbors (x,y))
|(alive (x,y)) = Nothing
|otherwise = [] ++ (x,y)
例子:
sort (deadNeighbors single) == sort [(41.41), (41.42), (41.43), (42.41), (42.43), (43.41), (43.42) , (43.43)]
sort (deadNeighbors row) == sort [(9.0), (9.1), (9.2), (10.0), (11.0), (11.1), (11.2) , (9.3), (11.3), (9.4), (10.4), (11.4)]
讓我們逐行通過deadNeighbors
go function:
(類型簽名看起來不錯)
deadNeighbors (neighbors (x,y))
這是deadNeighbors
function 的子句,似乎使用模式匹配符號,但是您在模式匹配中使用 function neighbors
。 那是不允許的。 我真的不知道你的意圖是什么,所以我不能建議解決這個問題的方法。
|(alive (x,y)) = Nothing
在這里你正確地使用了一個守衛,但是alive
的 function 除了坐標之外還需要生成。 您應該在此處將兩者作為 arguments 傳遞。
此外,您將返回Nothing
類型為Maybe a
的某些a
。 但是deadNeighbors
function 的簽名表明它應該返回一個[Coordinate]
。 也許你打算寫[]
(空列表)?
|otherwise = [] ++ (x,y)
這里您使用了++
運算符,它需要兩個列表作為 arguments,一個空列表[]
作為參數和一個坐標(x,y)
。 坐標類型不是列表,因此與++
運算符不兼容。 也許您打算(x,y): []
或只是[(x,y)]
(意思相同但稍微漂亮一點)?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.