我正在为我的班级工作,其中一个要求是创建一个名为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”。 如何打印其余部分?
答案 0 :(得分:5)
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