Search code examples
haskelllazy-evaluationnumber-theory

Infinite lazy lists of digits


So I'm trying to do some number theory work, and I was using Mathematica but thought that Haskell would be more suited to dealing with infinite lists (as AFAIK Mathematica doesn't have lazy evaluation). What I want to do is have Haskell store all the digits of 1/x in an infinite lazy list. So far my searching has not turned up a way to split a ratio into its digits that returns a list of digits rather than an actual floating point number.


Solution

  • We can also implement this as a simple stream producer:

    divDigits :: Int -> Int -> [Int]
    divDigits x y = x `div` y : divDigits (10 * (x `mod` y)) y
    

    There are actually libraries for this kind of "infinite"-precision number representation using lazy lists, see Haskell Wiki.