import Prelude hiding (take, repeat, iterate) fromTo :: Int -> Int -> [Int] fromTo n m = if n>m then [] else n : fromTo (n+1) m -- List of all ascending numbers starting from its argument: from :: Int -> [Int] from n = n : from (n+1) -- Computes the prefix of a maximal given length from a list take :: Int -> [a] -> [a] take n xs | n <= 0 = [] | otherwise = case xs of [] -> [] (x:xs) -> x : take (n-1) xs -- Compute the infinite list of all primes. sieve :: [Int] -> [Int] sieve (p:xs) = p : sieve (filter (\x -> x `mod` p /= 0) xs) primes :: [Int] primes = sieve (from 2) -- The list of all Fibonacci numbers: fibs :: [Int] fibs = fibgen 0 1 where fibgen :: Int -> Int -> [Int] fibgen n1 n2 = n1 : fibgen n2 (n1 + n2) -- A Fibonacci number: fib :: Int -> Int fib n = fibs !! n -- Infinite list of identical elements: repeat :: a -> [a] repeat x = x : repeat x -- Infinite list of iterative applications of a function: iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) -- Arithmetic list with an increment defined by the first two elements: fromThen :: Int -> Int -> [Int] fromThen n1 n2 = iterate (+ (n2-n1)) n1 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] -- [n..] enumFromTo :: a -> a > [a] -- [n..m] enumFromThen :: a -> a -> [a] -- [n1,n2..] enumFromThenTo :: a -> a -> a -> [a] -- [n1,n2..m] -- Instances of Enum: Int, Float, Char, Bool, Ordering class Bounded a where minBound, maxBound :: a -} data Color = Red | Yellow | Blue | Green deriving (Eq, Show, Enum, Bounded) -- Factorial function: fac :: Int -> Int fac n = foldr (*) 1 [1 .. n] -- An infinite list of numbered line strings: numLines :: [String] numLines = map (uncurry (++)) (zip (map show [1..]) (repeat ". line")) -- Example to demonstrate sharing: double :: Int -> Int double x = x + x dd3 :: Int --dd3 = double (double 3) -- Normalisation: identify each subterm by a variable: dd3 = let y = 3 z = double y in double z