[英]Why my output is “()” and how can i fix it?
我確實使用 txt 文件中的文本旋轉,我堅持最簡單的事情 - output 回到同一個文件。 在程序結束時,“()”出現在測試文件(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')
在程序的最后,
()
出現在測試文件中(output.txt
)
那么它寫()
的原因是因為 main2 的簽名是main2
main2:: IO ()
。 這意味着output
<- main2 中的output <- main2
將是單元類型[wiki] ,因此show ()
將返回字符串"()"
。
但實際上你首先不需要在這里使用mapM_
。 您可以制作一個 function ,它將為給定的[[Char]]
生成一個字符列表,例如:
rotateImg :: (Int -> Int -> Char) -> [Int] -> [Int] -> [[Char]]
rotateImg getPix ys xs = [
[ getPix (floor x) (floor y) | x' <- xs, let (x, y) = rotate (pi/3) (fromIntegral (x'-5), fromIntegral (y'-1)) ]
| y' <- ys
]
那么我們可以main
定義一個 function 讀取圖像信息,旋轉圖像,最后將旋轉后的圖像寫入文件(或將其打印到標准輸出):
main :: IO ()
main = do
image <- lines <$> readFile "input.txt"
let image2 = rotateImg (getPixel image) [0..30] [0..40]
writeFile "output.txt" (unlines output)
main2:: IO ()
更改為main2:: [Char]
。 哦,還有mapM_
到mapM
。
我看不到其他任何東西,所以應該可以解決它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.