Safe Haskell | Safe-Inferred |
---|---|
Language | Haskell2010 |
The naive left fold to convert digits to integer is quadratic
as multiplying (big) Integer
s is not a constant time operation.
This module provides sub-quadratic algorithm for conversion of Text
or ByteString
into Integer
.
For example for a text of 262144 9 digits, fold implementation
takes 1.5 seconds, and textToInteger
just 26 milliseconds on my machine.
Difference is already noticeable around 100-200 digits.
In particular read
is correct (i.e. faster) than List.foldl'
(better complexity),
stringToInteger
is a bit faster than read
(same complexity, lower coeffcient).
Synopsis
- textToInteger :: Text -> Integer
- byteStringToInteger :: ByteString -> Integer
- stringToInteger :: String -> Integer
- stringToIntegerWithLen :: String -> Int -> Integer
Documentation
textToInteger :: Text -> Integer Source #
byteStringToInteger :: ByteString -> Integer Source #
Convert ByteString
to Integer
.
Semantically same as BS.foldl' (acc c -> acc * 10 + toInteger c - 48) 0
,
but this is more efficient.
>>>
byteStringToInteger "123456789"
123456789
For non-decimal inputs some nonsense is calculated
>>>
byteStringToInteger "foobar"
6098556
stringToInteger :: String -> Integer Source #
stringToIntegerWithLen :: String -> Int -> Integer Source #
Convert String
to Integer
when you know the length beforehand.
>>>
stringToIntegerWithLen "123" 3
123
If the length is wrong, you may get wrong results. (Simple algorithm is used for short strings).
>>>
stringToIntegerWithLen (replicate 40 '0' ++ "123") 45
12300
>>>
stringToIntegerWithLen (replicate 40 '0' ++ "123") 44
1200
>>>
stringToIntegerWithLen (replicate 40 '0' ++ "123") 42
12