繁体   English   中英

我的 haskell 代码可能有什么问题,我该如何解决?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM