import Prelude hiding (take, repeat, iterate) -- Returns an ascending list of integers -- from 0 --> 0 : 1 : 2 : 3 : ... --from :: Int -> [Int] --from n = n : from (n + 1) -- Returns the first n elements of a list take :: Int -> [a] -> [a] take n xs | n == 0 = [] | otherwise = case xs of [] -> [] (x:xs) -> x : take (n-1) xs -- Sieve of Eratosthenes: filter multiples of initial elements sieve :: [Int] -> [Int] sieve (p:xs) = p : sieve (filter (\x -> x `mod` p > 0) xs) -- The infinite list of all prime numbers: primes :: [Int] primes = sieve (from 2) -- All Fibonacci numbers: -- Generator starting with two given Fibonacci numbers: fibgen :: Integer -> Integer -> [Integer] fibgen n1 n2 = n1 : fibgen n2 (n1 + n2) fibs :: [Integer] fibs = fibgen 0 1 -- An infinite list of some element repeat :: a -> [a] repeat x = x : repeat x -- Infinite list of applications of a function to some element. iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) -- Infinite list of 1: cyclic structure in Haskell ones :: [Int] ones = 1 : ones double :: Integer -> Integer double x = x + x fib100_double = double (fibs !! 100) fib100_plus = (fibs !! 100) + (fibs !! 100) ------------------------------------------------------------------------- -- [n ..] from :: Int -> [Int] from n = iterate (+1) n -- [n1,n2 ..] fromThen :: Int -> Int -> [Int] fromThen n1 n2 = iterate (+ (n2 - n1)) n1 -- [n .. m] fromTo :: Int -> Int -> [Int] fromTo n m = if n > m then [] else n : fromTo (n+1) m -- [n1,n2 .. m] fromThenTo :: Int -> Int -> Int -> [Int] fromThenTo n1 n2 m = let d = n2 - n1 in if (d >= 0 && n1 > m) || (d < 0 && n1 < m) then [] else n1 : fromThenTo (n1+d) (n2+d) m {- class Enum a where succ,pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] enumFromThen :: a -> a -> [a] enumFromTo :: a -> a -> [a] enumFromThenTo :: a -> a -> a -> [a] -- Instances: Int, Float, Char, Bool, Ordering -} {- -- Types with a minimum and a maximum value: class Bounded a where minBound, maxBound :: a -- Instances: Int, Char, Bool, Ordering -} data Color = Red | Blue | Green deriving (Show,Enum,Bounded) -- ["1. line: ","2. line: ",...] numLines :: [String] numLines = map (uncurry (++)) (zip (map show [1 ..]) (repeat ". line: ")) ------------------------------------------------------------------------- -- List comprehensions: Examples -- Odd numbers odds :: [Int] odds = [ x | x <- [1 .. 100], odd x ] -- Doubled odd numbers dodds :: [Int] dodds = [ x+x | x <- [1 .. 100], odd x ] -- Some pairs of integers pairs :: [(Int,Int)] pairs = [ (i,j) | i <- [1 .. 3], j <- [3 .. 8] ] -- All prefixes of list of naturals. prefixes :: [[Int]] prefixes = [ [0 .. n ] | n <- [1 ..] ] -- All factorial numbers. facs :: [Integer] facs = map (foldr (*) 1) [ [1 .. n] | n <- [1 ..]] -- Some triples of integers triples :: [(Int,Int,Int)] triples = [ (x,y,z) | x <- [1..4], y <- [2..6], let z = x+y, x /= y ]