Defining an infinite list in Haskell of the same int, how?

Defining an infinite list in Haskell:

[1,1..] => [1,1,1,..] 

Or a circular path:

 lst=1:lst 

Is the first defined the same as the second? If not, which one is preferred?

+4
source share
4 answers

You probably want to repeat where the definition is equivalent to your second implementation.

The notation [1,1..] in your first example is syntactic sugar for the enumFrom* foreplay functions. Use what you prefer.

+6
source

repeat / 1:lst better, they do not require additional calculations, but [1,1..] does:

 [1,1..] = enumFromThen 1 1 = en 1 where en n = n : en (n + nΞ”) nΞ” = 1-1 = 0 

therefore, it is always necessary to perform an additional 1+0 .

+6
source

If you're out of luck, your first infinite list will use an infinite amount of memory. So use your second infinite list (or, if you prefer an anonymous infinite list, use repeat from Prelude).


Demonstration. Perhaps run watch free -m in another window by doing this.

 $ cat so.hs import Control.Exception (evaluate) import System.IO (hFlush, stdout) with :: String -> [Int] -> IO () with s xs = do putStrLn $ "Summing part of a " ++ s theSum <- evaluate $ sum (take 100000000 xs) firstElem <- evaluate $ head xs putStrLn $ "sum $ take 100000000 [" ++ show firstElem ++ "...] is " ++ show theSum main :: IO () main = do with "call to repeat" (repeat 1) putStr "Press return to continue..." hFlush stdout getLine with "list comprehension" [1,1..] $ ghc -O --make so.hs [1 of 1] Compiling Main ( so.hs, so.o ) Linking so ... $ ./so Summing part of a call to repeat sum $ take 100000000 [1...] is 100000000 Press return to continue... Summing part of a list comprehension ^C 

The first summation is performed in constant space. The second summation consumes memory, so I interrupt it before it forces my laptop to swap.

In this simple case, we could avoid a space leak by calculating firstElem before calculating theSum , but in the real world this may not be possible, or at least difficult to track. It is better to avoid this using repeat .

(Optimization note: if we do not pass the -O flag to ghc , then sum will leak into space during both summations. It is difficult to rewrite sum = foldl' (+) 0 so that it does not leak even without -O . I don’t know which considerations lead to the current implementation instead.)

+4
source

To answer your question, both expand, but the let and repeat options are better, because the enumFrom option goes through the actual enumeration, so useless arithmetic is involved.

+3
source

All Articles