【问题标题】:Haskell Either in mainHaskell 无论是主要
【发布时间】:2021-03-11 05:55:59
【问题描述】:

我无法使用在我的 main :: IO() 函数中返回 Either monad 的函数。 我可以在不使用 Either 的情况下运行我的代码,但我现在使用 Either 来处理错误。 我有以下代码:

parse :: Parser a -> String -> Either TypeRep a
parseFile :: String -> Either TypeRep Game

main :: IO()
main = do 
  content <- readFile "file.txt"
  let info = parseFile content
  case info of
    Left e -> error $ show e
    Right game -> let level = makeGame game
               Gloss.play ... level ... 

所以如果我的解析函数刚刚返回 a,我的代码就能够执行 Gloss.play 等等。 如何使用 IO 在主中处理 Either。

【问题讨论】:

  • 您应该考虑使用System.Exit.die 而不是error。前者是定义明确的IO动作,导致程序退出;后者是一个未定义的IO 动作,并且允许不同的实现选择不同的行为(有一些限制——所以至少你不必像 C 那样担心鼻恶魔)。

标签: haskell io either gloss


【解决方案1】:

你已经接近了。在您的Right game -&gt; 案例中,您想引入另一个do-block,例如:

main :: IO()
main = do 
  content <- readFile "file.txt"
  let info = parseFile content
  case info of
    Left e -> error $ show e
    Right game -> do
      let level = makeGame game
      Gloss.play ... level ... 

【讨论】:

    猜你喜欢
    • 2013-04-13
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2014-02-12
    • 2010-11-10
    • 2020-11-28
    • 2011-03-26
    相关资源
    最近更新 更多