Issue
I do work with text rotate from a txt file, I'm stuck on the simplest thing - output back to the same file. At the end of the program, “()” appears in the test file (output.txt). I know I need to rewrite main2
somehow, but I don’t know how exactly. There is problem with side effects, I think. So, what to do? I will be happy to get your help
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')
Solution
At the end of the program,
()
appears in the test file (output.txt
)
Well the reason it writes ()
is because the signature of main2
is main2 :: IO ()
. This means that output
in output <- main2
will be the unit type [wiki], and thus show ()
will return the string "()"
.
But you actually do not need to use mapM_
here in the first place. You can make a function that will, for a given [[Char]]
generate a list of chars, for example:
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
]
So then we can define in the main
a function that reads then image info, rotates the image, and finally writes the rotated image to a file (or prints it to the stdout):
main :: IO ()
main = do
image <- lines <$> readFile "input.txt"
let image2 = rotateImg (getPixel image) [0..30] [0..40]
writeFile "output.txt" (unlines output)
Answered By - Willem Van Onsem Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.