【问题标题】:Why my output is "()" and how can i fix it?为什么我的输出是“()”,我该如何解决?
【发布时间】: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 &lt;- main2 中的output 将是(),因此show output 将是"()"
  • mapM_改写为mapM,并将签名改为main2 :: IO [Char]
  • @WillemVanOnsem 您是否测试过这个提议的修复?我觉得不合适。
  • @DanielWagner:啊,是的,忘了mapM 中的putStrLn,好吧。在这里使用putStrLn 有点“奇怪”。你是对的。

标签: file haskell output


【解决方案1】:

程序结束时,()出现在测试文件中(output.txt

之所以写() 是因为main2 的签名是main2 :: IO ()。这意味着output &lt;- main2 中的output 将是unit type [wiki],因此show () 将返回字符串"()"

但实际上你首先不需要在这里使用mapM_。您可以创建一个函数,为给定的[[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 中定义一个函数,该函数读取图像信息,旋转图像,最后将旋转后的图像写入文件(或打印到标准输出):

main :: IO ()
main = do
    image <- lines <$> readFile "input.txt"
    let image2 = rotateImg (getPixel image) [0..30] [0..40]
    writeFile "output.txt" (unlines output)

【讨论】:

    【解决方案2】:

    main2 :: IO () 更改为main2 :: [Char]。哦,还有mapM_mapM

    我看不到其他任何东西,所以应该可以解决它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-14
      相关资源
      最近更新 更多