【发布时间】:2020-09-14 17:27:50
【问题描述】:
我确实使用 txt 文件中的文本旋转,我坚持最简单的事情 - 输出回同一个文件。在程序结束时,“()”出现在测试文件(output.txt)中。我知道我需要以某种方式重写main2,但我不知道具体如何。我认为副作用有问题。那么该怎么办?我很乐意得到您的帮助
import System.IO
getPixel :: [[Char]] -> Int -> Int -> Char
getPixel img x y
| x >= 0 && x < width && y >= 0 && y < height = img !! y !! x
| otherwise = ' '
where
height = length img
width = length $ head img
rotate :: Double -> (Double, Double) -> (Double, Double)
rotate a (x, y) = (x * cos a + y * sin a, -x * sin a + y * cos a)
main :: IO ()
main = do
output <- main2
writeFile "output.txt" (show output)
main2 :: IO ()
main2 = do
image <- lines <$> readFile "input.txt"
mapM_ putStrLn $ do
y <- [0 .. 30]
return $ do
x <- [0 .. 40]
let (x', y') = rotate (pi/3) (x-5, y-1)
return $ getPixel image (floor x') (floor y')
【问题讨论】:
-
由于
main2的类型为IO (),这意味着output <- main2中的output将是(),因此show output将是"()"。 -
将
mapM_改写为mapM,并将签名改为main2 :: IO [Char]。 -
@WillemVanOnsem 您是否测试过这个提议的修复?我觉得不合适。
-
@DanielWagner:啊,是的,忘了
mapM中的putStrLn,好吧。在这里使用putStrLn有点“奇怪”。你是对的。