【发布时间】:2019-01-03 23:27:04
【问题描述】:
以下定义表示由网格上特定坐标处的彩色方块组成的形状:
type AltShape = [Point]
data Point = P Colour (Int,Int) deriving Eq
data Colour = Black | Red | Green | Blue deriving Eq
我应该假设坐标总是正数,坐标(0,0)指的是图片的左上角,y坐标向下增长
红色的 L 形可以表示为
lShape = [P Red (0,0), P Red (0,1), P Red (0,2), P Red (1,2)]
表示这种形状的另一种方法是列表列表,每行一个列表:
type Shape = [Row]
type Row = [Square]
type Square = Maybe Colour
例如,上面的红色 L 形将由以下 Shape 类型的值表示:
lShape2 = [[x,o]
,[x,o]
,[x,x]] where x = Just Red
o = Nothing
我的任务是定义一个函数toShape :: AltShape -> Shape,它将AltShape 转换为Shape。我有另一个任务来定义一个函数fromShape :: Shape -> AltShape,但是data Shape = S [Row] 在哪里。我发现这很简单,并这样写:
fromShape :: Shape -> AltShape
fromShape (S rows) = [ P c (x,y) | (y,row) <- index rows, (x,Just c) <- index row]
where index = zip [0..]
但是,我在这个问题上遇到了更多麻烦。我从创建函数开始
colourAndCoords :: Point -> (Colour,(Int,Int))
colourAndCoords ( P c (x,y) ) = (c,(x,y))
然后我创建了一个函数
coords :: [Point] -> [(Int,Int)]
coords ps = map snd (map colourAndCoords ps)
我的想法是将这个列表与所有可能的协调的另一个列表进行比较,在有匹配的地方添加正确的颜色,在没有匹配的地方我会添加任何内容。但是,我的老师说我把它弄得太复杂了,我应该考虑另一种解决方案。但我很难想到一个。所以我想我的问题是更简单的方法是什么?我不是在寻求解决方案,只是朝着正确的方向轻推。
非常感谢花时间阅读本文并回复的任何人!
如果我想出一个解决方案,我会回来更新这个帖子。
【问题讨论】:
标签: haskell