如果使用ord
,该类型匹配,但它不是你想要的,因为ord
给你 ASCII值,而不是数值:ord 5
是53
,不5
。您可以减去 48以获取数字,然后将数字向上滚动到一个数字中,但它会更容易使用库函数。最简单的选择是read
:
getInt :: IO Integer
getInt = do
y <- readFile "foo.txt"
return (read (takeWhile (/='\n') y))
正如linked answer, 这里最好的解决方案是使用reads
。
reads
发现可能匹配的列表, 作为对(match,remainingstring)
, 这是因为它会自动离开换行符剩余的字符串为你工作得很好,
*Main> reads "31324542\n" :: [(Integer,String)]
[(31324542,"\n")]
让我们使用即:
findInt :: String -> Maybe Integer
findInt xs = case reads xs of -- have a look at reads xs
((anint,rest):anyothers) -> Just anint -- if there's an int at the front of the list, just return it
_ -> Nothing -- otherwise return nothing
Maybe
是一种方便的数据类型,可以让您在没有崩溃程序或执行异常处理的情况下发生故障。 Just 5
意味着你得到了输出,它是5
。 Nothing
意味着有问题,没有输出。
addTen :: FilePath -> IO()
addTen filename = do
y <- readFile filename
case findInt y of
Just i -> putStrLn ("Added 10, got "++show (i+10))
Nothing -> putStrLn ("Didn't find any integer at the beginning of " ++ filename)
它给你:
*Main> addTen "foo.txt"
Added 10, got 1234567890
如果你只是想字符代表的整数,你可以在你的文件的顶部放import Data.Char
做
ordzero = ord '0' -- handy constant, 48, to unshift the ascii code to a digit.
getInts :: FilePath -> IO [Int] -- ord gives the smaller Int, not Integer
getInts filename = do
y <- readFile filename
return [ord achar - ordzero | achar <- takeWhile isDigit y]
这需要字符串y
的人物,只要他们的数字,然后 发现自己ord
,减去ord '0'
(这是48)把'4'
为4
等
这个问题可能会有所帮助:http://stackoverflow.com/questions/2468410/convert-string-to-integer-float-in-haskell – jrajav