-- List continued... -- A small Introduction to Lists and List Comprehensions -- Lists myLottoNumbers :: [Int] -- a list of Int myLottoNumbers = [18,24,66,91,97] winningLottos :: [[Int]] -- a list of lists of Int winningLottos = [myLottoNumbers,[18,22,66,91,99],[20,30,40]] validNumbers :: [Int] validNumbers = [1..99] -- a built-in function to generate a list fac :: Integer -> Integer fac n = product [1..n] -- factorial function -- Example standard functions -- (++), reverse, length, sum, product, maximum, ... -- Lots more in module Data.List -- The truth about String (saw that in the Kahoot) ---------------------------------------------- -- List Comprehensions power2table :: Integer -> [Integer] -- power2table n gives a list of powers of 2 from 0 up to n -- power2table 7 == [1,2,4,8,16,32,64,128] power2table n = -- undefined [ 2^x | x <- [0..n]] sumsquares n = sum [x*x | x <- [1..n]] -- Multiple Generators example2generators = [x+y | y <- [100,200], x <- [1,2,3] ] -- Guards powersUpto :: Integer -> [Integer] -- powersUpto n gives all powers of 2 no larger than n powersUpto n = [p | p <- power2table n, p <= n] --- Prime numbers -- A prime number n has factors 1 and n and no others. -- 1,2,5 and 10 are factors of 10 (so 10 is not a prime). -- isFactor of n m gives True if n is a factor of m isFactorOf :: Integer -> Integer -> Bool n `isFactorOf` m = m `mod` n == 0 -- using a function as an operator -- can be good for readability primes :: Integer -> [Integer] primes n = [ c | c <- [2..n], factors c == [1,c]] where -- this is a local definition factors m = [k | k <- [1..m], k `isFactorOf` m ]