您可以使用read 来解析整数或浮点数。
它位于 Prelude 中,因此您无需任何其他模块即可使用它。
试试:
a = "0xFF5FFFC8EC5FFEDF"
b = read a::Double
(它给出 b = 1.8401707840883393e19)
另外,为了解析 CSV,您也可以创建自己的函数来执行此操作。
一周前我刚刚写了一个简单的 CSV 解析器。
module CSVUtils
( parseCSV, showCSV
, readCSV , writeCSV
, colFields
, Separator, Document
, CSV , Entry
, Field
)
where
import Data.Char
import Data.List
{-
A simple utility for working with CSV (comma-separated value) files. These
are simple textual files where fields are delimited with a character (usually a comma
or a semicolon). It is required that the CSV document is well-formed, i.e., that
it contains an equal number of fields per row.
-}
type Separator = String
type Document = String
type CSV = [Entry]
type Entry = [Field]
type Field = String
doc = "John;Doe;15\nTom;Sawyer;12\nAnnie;Blake;20"
brokenDoc = "One;Two\nThree;Four;Five"
{-
(a) Takes a separator and a string representing a CSV document and returns a
CSV representation of the document.
-}
-- !! In the homework text is said Separator is going to be Char and now the type is String
-- !! so I'm just going to take head
parseCSV :: Separator -> Document -> CSV
parseCSV sep doc
| (head sep) `notElem` doc = error $ "The character '"++sep++"' does not occur in the text"
| 1 /= length ( nub ( map length (lines doc))) = error $ "The CSV file is not well-formed"
| otherwise = [splitOn sep wrd | wrd <- lines doc ]
{-
(b) Takes a separator and a CSV representation of
a document and creates a CSV string from it.
-}
showCSV :: Separator -> CSV -> Document
showCSV sep = init . unlines . map (intercalate sep)
{-
(c) Takes a CSV document and a field number
and returns a list of fields in that column.
-}
colFields :: Int -> CSV -> [Field]
colFields n csv = [ if length field > n
then field !! n
else error $ "There is no column "++(show n)++" in the CSV document"
| field <- csv]
{-
(d) Takes a file path and a separator and returns the CSV representation of the file.
-}
readCSV :: Separator -> FilePath -> IO CSV
readCSV sep path = do
file <- readFile path
return $ parseCSV sep file
{-
(e) Takes a separator, a file path, and a CSV document and writes the document into a file.
The return type of writeCSV is a special case of IO { we need to wrap an impure
action, but do not actually have to return anything when writing. Thus, we
introduce (), or the unit type, which holds no information (consider it a 0-
tuple).
-}
writeCSV :: Separator -> FilePath -> CSV -> IO ()
writeCSV sep path csv = writeFile path (showCSV sep csv)