Read type class

I just realized that the prelude doesn’t have a Read type class.

Does anyone know any history behind this? I assume this was a conscious decision.

I tried searching the issues in the purescript and purescript-prelude repos on GitHub but there were a lot of results and none seemed relevant.

1 Like

Perhaps purescript-in-purescript had this at some point. I’ll try looking there.

I’m starting to think this probably comes down to having to maintain a PureScript parser in PureScript, since it seems like it should work in theory at runtime.

AFAIK, this was intentionally left out. Haskell from First Principles recommends never using this type clsas. I think we only have Show so that one can print things from the REPL. However, even that type class is discouraged despite everyone using it.

1 Like

Yeah, it’s definitely not something I miss. It’s rarely a good idea to use, I think; proper serialization tools are preferable. (Show kind of sucks for serialization anyway.) I don’t think it comes down to having to maintain a PureScript parser in PureScript; if you were going to go that route you would have to implement a PureScript evaluator too and that would be massively overkill, because the following approach suffices:

instance readMaybe :: Read a => Read (Maybe a) where
  read str = parseJust <|> parseNothing
    parseJust = do
      inner <- str # stripPrefix "(Just " >=> stripSuffix ")"
      read inner

    parseNothing = do
      guard (str == "Nothing")
      pure Nothing    

I think GHC generates code along these lines when you ask it to derive Read. For data types where you do need a conversion from string, those functions should be provided as monomorphic functions, in my view. For example: Data.Int.fromString :: String -> Maybe Int.

1 Like

Yup, it was all this. If we’d defined it we would have wanted to make it support failure without crashing also, making it even more parser-like, so why not just use a real serialization format, etc.

I mean, in addition to that, we’re still not all that enthused about Show either really. :smile:

1 Like