2012-02-24 44 views
2

我有一個名爲PartialDateHaskell的閱讀 - 沒有語法錯誤

然後,我有一個函數的

readPartialDate :: String -> Maybe PartialDate 

位測試碼型

main = do 
     [d] <- getArgs 
     return $ show $ readPartialDate d 
runhaskell PartialDate.hs "12-2-2010" 
"Just 12-2-2010" 

一切OK

然後,我只是被派遣上readPartialDate創建讀:

instance Read PartialDate where 
     readsPrec _ s = case (readPartialDate s) of 
           Nothing -> [] 
           Just p -> [(p, s)] 

測試代碼:

main = do 
     [d] <- getArgs 
     return $ show $ ((read d) :: PartialDate) 
runHaskell PartialDate.hs 12-2-2010 
PartialDate.hs: Prelude.read: no parse 

有誰知道爲什麼把工作職能轉變爲讀取可能會引起解析錯誤?

readPartialDate使用Parsec,也使用反轉,所以在這裏可能會出現懶惰問題?

回答

4

的問題是,在readsPrec定義,

readsPrec _ s = case (readPartialDate s) of 
         Nothing -> [] 
         Just p -> [(p, s)] 

你給輸入字符串本身作爲readsPrec結果對第二組件。 read要求reads結果有第二個組件爲空,這意味着整個輸入已被用於確定值(通常,當您編寫Read實例時,請確保您不要忘記消耗尾隨空白)。更改實例爲

readsPrec _ s = case (readPartialDate s) of 
         Nothing -> [] 
         Just p -> [(p, "")] 

它應該工作。

+0

太棒了。謝謝丹尼爾 – 2012-02-24 11:05:40

+0

@RobertOnslow:如果這回答了你的問題,請記住標記爲這樣。 – ivanm 2012-02-24 11:26:29