我有以下代碼:Haskell中的異常如何工作(第二部分)?
crabgrass:~/tmp/signserv/src% ghc -fforce-recomp Main.hs && ./Main
Main: WrongArgumentCount
crabgrass:~/tmp/signserv/src% ghc -O -fforce-recomp Main.hs && ./Main
Main: Main.hs:20:9-34: Irrefutable pattern failed for pattern [portStr, cert, pw]
爲什麼是這樣的:
{-# LANGUAGE DeriveDataTypeable #-}
import Prelude hiding (catch)
import Control.Exception (throwIO, Exception)
import Control.Monad (when)
import Data.Maybe
import Data.Word (Word16)
import Data.Typeable (Typeable)
import System.Environment (getArgs)
data ArgumentParserException = WrongArgumentCount | InvalidPortNumber
deriving (Show, Typeable)
instance Exception ArgumentParserException
data Arguments = Arguments Word16 FilePath String
main = do
args <- return []
when (length args /= 3) (throwIO WrongArgumentCount)
let [portStr, cert, pw] = args
let portInt = readMaybe portStr :: Maybe Integer
when (portInt == Nothing) (throwIO InvalidPortNumber)
let portNum = fromJust portInt
when (portNum < 0 || portNum > 65535) (throwIO InvalidPortNumber)
return $ Arguments (fromInteger portNum) cert pw
-- Newer 'base' has Text.Read.readMaybe but alas, that doesn't come with
-- the latest Haskell platform, so let's not rely on it
readMaybe :: Read a => String -> Maybe a
readMaybe s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
其行爲因與時開啓和關閉的優化編譯?我知道imprecise exceptions can be chosen from arbitrarily;但是我們在這裏選擇的是一個精確的和一個不精確的例外,所以這個警告不應該適用。
這看起來像是一個bug。你正在使用哪個GHC版本?我看到與GHC 7.6.2相同的行爲。 – hammar
@hammar它至少在7.6.1和7.4.1這裏發生,並且在#haskell中提到它的人使用了7.0.x. –
@DanielWagner這很奇怪,因爲在7.0.2和7.0.4上,我得到了'WrongArgumentCount'。 (也是6.12.3) –