首页 > 解决方案 > 如何使此功能在列表中添加任何内容?

问题描述

有什么方法可以在列表理解中将 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 的列表。我应该如何以不同的方式写它?

标签: haskell

解决方案


使用警卫

toShape :: AltShape -> Shape
toShape ps = splitEvery (rowLength ps) 
            [ (lookup row (table ps)):r 
            | row <- allCoords (colLength ps) (rowLength ps)
            , row `notElem` (map coords ps) ]

推荐阅读