i have a data structure like this
data Something = Something Integer String String
and i want to convert
["Something", "3", "text", "42"]
to the data.
for now, i have
altRead :: Read a => [String] -> a
altRead = read . unwords . hack
where
hack = map (\x -> if isNumber x then x else "\"" ++ x ++ "\"")
isNumber = foldl (\b c -> isDigit c && b) True
but i forgot, that some numbers could be strings in the data structure.
is there a simple solution for this or do i need to write a alternative read typeclass?
You’re writing a tiny parser atop some lexed tokens. You can’t really implement a
Readinstance sinceread :: Read a => String -> aand you want to do[String] -> afora == Something. You can take advantage ofReadinstances that already exist, though, to bootstrap parsing yourInteger, for instance.So let’s try it. We’ll parse a
Somethingfrom the list of tokens.We could do it a little more compactly using
Maybeas anApplicative, tooReally, we should probably return any unconsumed tokens as well so we can continue parsing.
The reason I bring in all this structure to your parse is that this starts to head toward the space of parser combinators like
Parsec. Whenever you’ve got a need for a complicatedReadit begins to become useful to look at some of the really nice parsing libraries in Haskell.