There are some source files, which are in S-expressions. Can Haskell read those s-expressions? I need those s-expressions as patterns mat开发者_JAVA百科ched to execute the Haskell programs (suppose those s-expressions are already in the format of my haskell program data types) . For example,
The S-expression in the file is: ArithBiOp Plus (AInt 5) (AInt 5)
, then in the haskell program, I can match this line as ArithBiop opcode oprand1 operand2
.
If you're asking whether there's some built-in method for reading data from such files, then the answer is no, not really.
The standard type classes Read
and Show
are a sort of poor-man's serialization that do something similar, with the expectations that read (show x)
== x
and that the output of show x
, evaluated as Haskell source, is also equal to x
. However, if you have arbitrary expressions from some other source it's probably not safe to assume they'll match the format expected by read
, even if (as in your example) they'll be very similar.
On the other hand, S-expressions are approximately the easiest thing to parse in the world, so it would probably be trivial to bang out something with Parsec or such to read your data.
If you can sufficiently constrain the input to be confident that it will match the output of show
you'd get from the default instance for your types, though, then read
ought to work. Note that the default Read
instances are at least somewhat robust to things like spurious parentheses and whitespace:
> read " Just 1" :: Maybe Int
Just 1
> read " Just 1" :: Maybe Int
Just 1
> read " Just (1)" :: Maybe Int
Just 1
> read "(Just (1))" :: Maybe Int
Just 1
And so on.
Oh, and if you're asking about how to get the data from the files, you don't need to do anything special. Just use the same file I/O you'd use for anything else and give the strings to read
or a parser. For simple stuff the System.IO
module should do everything you need.
In the extremely simple case of using read
and having one value per line, read from stdin, the readLn function is a convenient shortcut.
If you are lucky you might be able to craft a data type that has exactly the right form to use read
to get you data from file. For you example:
data Exp = ArithBiOp Op Exp Exp | AInt Integer deriving (Show, Read)
data Op = Plus | Minus deriving (Show, Read)
Then you can just use readFile
to get a string and convert that with read
.
精彩评论