haskell - 如何使此功能在列表中添加任何内容?
问题描述
有什么方法可以在列表理解中将 Nothing 添加到列表中?
我写了以下函数
toShape :: AltShape -> Shape
toShape ps = splitEvery (rowLength ps)
[ if (row `notElem` (map coords ps))
then (lookup row (table ps)):r
else Nothing
| row <- allCoords (colLength ps) (rowLength ps) ]
其中 AltShape 和 Shape 定义为:
type AltShape = [Point]
data Point = P Colour (Int,Int) deriving (Eq,Show)
type Shape = [Row]
type Row = [Square]
type Square = Maybe Colour
data Colour = Black | Red | Green deriving (Eq,Show)
基本上,该函数应该将 AltShapes 转换为 Shapes。我一直试图通过创建一个函数来实现这一点,该函数根据形状的宽度和高度创建所有可能的坐标,然后将它们与形状中的实际点匹配。如果有匹配项,我想将 Just c 添加到列表中,其中 c 是颜色,如果没有匹配项,我希望它在列表中添加 Nothing。但现在我只得到了一个 Just c 的列表。我应该如何以不同的方式写它?
解决方案
使用警卫
toShape :: AltShape -> Shape
toShape ps = splitEvery (rowLength ps)
[ (lookup row (table ps)):r
| row <- allCoords (colLength ps) (rowLength ps)
, row `notElem` (map coords ps) ]
推荐阅读
- kubernetes - Pod 状态失败的原因
- clips - Clips 6.4 IDE 潜在错误。未显示所选模块的事实
- r - 运行 featuretoolsR 时出现词法错误
- angular - 在 chrome 开发者工具的预览和响应选项卡中获得不同的价值
- php - PHP发布如何在foreach循环中获取选项值以显示所选值
- javascript - Express.js 路由中是否有通配符?
- c++ - 对运算符删除覆盖的工作方式感到困惑
- apache-kafka - 在启用 tls 和基于 kafka 的排序的情况下设置 HLF 网络 V1.4
- linux - 如何为每个文件名以及目录中文件内容的每一行添加序列号,例如 1、2、3 等?
- elasticsearch - 如何用 Elasticsearch 中的另一个字段覆盖 @timestamp 字段?