2

我目前正在为我的班级分配作业,其中一个要求是创建一个名为 rotate90 的函数。这个函数基本上接受一个 [[Char]] 并将其顺时针旋转 90 度。

例如:

type Picture = [[Char]]
pic :: Picture
pic = [ "123",
    "456",
    "789" ]

变成:

[ "741",
  "852",
  "963" ]

到目前为止,我的代码看起来像这样:

rotate90 :: Picture -> Picture
rotate90 (x:xs)
    | (x:xs) == []          = []
    | xs == [] && x /= []   = formRow ([[]]) (formCol x)
    | xs /= []              = formRow (rotate90 xs) (formCol x)


formCol :: [Char] -> [[Char]]
formCol y = [[a] | a <- y]

formRow :: [[Char]] -> [[Char]] -> [[Char]]
formRow (x:xs) (y:ys)
    | xs == [] || ys == []  = (x++y):[]
    | otherwise             = (x++y):formRow xs ys

现在它只打印矩阵的第一“行”,在示例中是“741”。如何让它打印其余部分?

4

1 回答 1

6

一个简单的实现Data.List.transpose

-- | Rotate clockwise
cw = map reverse . transpose
-- | Rotate counter-clockwise
cw = reverse . transpose

转置原始图片会产生

147
258
369

并反转每一行导致旋转的图片

741
852
963

通常,您可以使用以下三个函数的组合来表示任意方向的镜像和旋转:

transpose
map reverse -- mirror left <-> right
reverse -- mirror top <-> bottom
于 2013-02-04T12:29:16.520 回答