Haskell Infinite Lists

  • Lazy Lists (Finite)
  • 
                [1 .. 10]    -- Python: range(1, 11)
                [2, 4 .. 10] -- Python: range(2, 11, 2)
                
  • Lazy Lists (Infinite)
  • 
                [1 ..]       -- [1, 2, 3, 4, ...]
                [1, 1 ..]    -- [1, 1, 1, 1, ...]
                [2, 4 ..]    -- [2, 4, 6, 8, ...]
                [4, 8 ..]    -- [4, 8, 12, 16, ...]
                
  • take - process only part of a list
  • 
                take :: Int -> [a] -> [a]
                take _ [] = []
                take 0 _ = []
                take n (h:t) = h : take (n - 1) t
                -- the below gets [3, 6, 9, 12, 15]
                take 5 [3, 6, ..]
                

Haskell Infinite Lists

  • Infinite Lists by Recursion
  • 
                plus2 :: Int -> [Int]
                plus2 n = n : plus (n + 2)
                
                odds :: [Int]
                odds = plus2 1
                
                evens :: [Int]
                evens = plus2 2
                
  • Infinite Lists by List Comprehensions
  • 
                integers = [x | x <- [1 ..]]
                odds = [x | x <- [1 ..], mod x 2 == 1]
                squares = [x^2 | x <- [1 ..]]
                

Haskell Infinite Lists

  • Infinite Lists of Fibonacci Sequence
  • 
                nextfib :: Int -> Int -> [Int]
                nextfib x y = (x + y) : nextfib y (x + y)
                fibs :: [Int]
                fibs = [1, 1] ++ nextfib 1 1
                
  • Infinite Lists by Prime Numbers
  • 
                sieve :: [Int] -> [Int]
                sieve (x:xs) = x : 
                  seive [y | y <- xs, mod y x /= 0]
                primes :: [Int]
                primes = sieve [2 ..]