为什么这个 Read 实例解析不一致?
import qualified Data.List as List
data Foo = Foo
instance Show Foo where
show _ = "Foo"
instance Read Foo where
readsPrec _ s = case List.stripPrefix "Foo" s of
Just rest -> [(Foo, rest)]
Nothing -> []
Run Code Online (Sandbox Code Playgroud)
这是预期的:
Test> reads "" :: [(Foo, String)]
[]
Run Code Online (Sandbox Code Playgroud)
这是出乎意料的:
Test> read "" :: Foo
Foo
Run Code Online (Sandbox Code Playgroud)
我希望它会抛出。
The problem isn't in read, but in show. Your show implementation doesn't force the input value of type Foo, because it returns "Foo" unconditionally, without even matching a constructor. If you use the derived Show instance, or write its equivalent by hand:
instance Show Foo where
show Foo = "Foo"
Run Code Online (Sandbox Code Playgroud)
then you will get the expected error when you try to parse a malformed string, because evaluating show will actually require parsing the input string.