Search code examples
haskellrandomhaskell-stackghci

Haskell sorted random list is infinite


For a small project I want to use Haskell. Need batches of 4 random numbers between 0 and 9, and these [Int] needs to be sorted when done (using: Data.Sort). Code below keeps returning an infinite list despite take 4 xs.

import System.Random 
import Data.Sort 

randomList :: IO () 
randomList = do 
  generator <- getStdGen 
  let rndGen = randomRs (0,9) generator :: [Int]
  getFourDigits <- return (fourDigits rndGen) 
  putStrLn $ show getFourDigits

fourDigits :: Ord a => a -> [a]
fourDigits rndGen = sort $ take 4 (repeat rndGen)

Is this caused by dry-running in stack ghci?


Solution

  • In short, your rndGen has as type an [Int]. So a list of Ints. This thus means that repeat rndGen has type [[Int]], so a list of lists of Ints. All these lists have infinite size.

    This thus means that if you want to sort that list, you compare the individual elements. But since these individual elements have infinite size, and are equal, that function will never terminate. If you want to determine if a list x is smaller than a list y, you can concurrently iterate over the two lists and stop from the moment the elements are different. But these elements are never different.

    You should implement your function as:

    fourDigits :: Ord a => [a] -> [a]
    fourDigits rndGen = sort $ take 4 rndGen