import Test.QuickCheck import System.Time import System.CPUTime ----------------------------------------------------------------------- slow :: Integer -> Integer slow n | n <= 1 = 1 | otherwise = slow (n-1) + slow (n-2) if' :: Bool -> a -> a -> a if' False x y = x if' True x y = y examp1 = if' False 17 (slow 99) ----------------------------------------------------------------------- strange :: Bool -> Integer strange False = 17 strange True = 17 examp2 = strange undefined ----------------------------------------------------------------------- ones :: [Integer] ones = 1 : ones examp3 = take 10 ones ----------------------------------------------------------------------- printTable :: [String] -> IO () printTable xs = sequence_ [ putStrLn (show i ++ ": " ++ x) | (x,i) <- xs `zip` [1..] ] examp4 = printTable ["Häst", "Får", "Snigel"] ----------------------------------------------------------------------- replicate' :: Int -> a -> [a] replicate' n x = take n (repeat x) ----------------------------------------------------------------------- pairs :: [a] -> [(a,a)] pairs xs = xs `zip` tail (cycle xs) -- alternative definition pairs' :: [a] -> [(a,a)] pairs' xs = xs `zip` tail (xs ++ xs) ----------------------------------------------------------------------- group :: Int -> [a] -> [[a]] group n = takeWhile (not . null) . map (take n) . iterate (drop n) ----------------------------------------------------------------------- data Labyrinth = Crossroad { what :: String , left :: Labyrinth , right :: Labyrinth } deriving ( Eq, Show ) labyrinth :: Labyrinth labyrinth = start where start = Crossroad "start" forest town town = Crossroad "town" start forest forest = Crossroad "forest" town exit exit = Crossroad "exit" exit exit ----------------------------------------------------------------------- -- Two alternative solutions. Which one's faster? -- prime numbers, checking for each x that all prime numbers up to the square -- root of x do not divide the number primes :: [Integer] primes = 2 : [ x | x <- [3,5..], isPrime x ] where isPrime x = all (not . (`divides` x)) (takeWhile (\y -> y*y <= x) primes) -- prime numbers using a naive sieve primes2 :: [Integer] primes2 = sieve [2..] where sieve (x:xs) = x : sieve [ y | y <- xs, not (x `divides` y) ] -- divides divides :: Integer -> Integer -> Bool a `divides` b = b `mod` a == 0 -- comparison whichOne = do t1 <- getCPUTime let ps1 = take n primes print (sum ps1) t2 <- getCPUTime let ps2 = take n primes2 print (sum ps2) t3 <- getCPUTime putStrLn $ (if t2-t1 < t3-t2 then "primes" else "primes2") ++ " is faster!" where n = 1000 -----------------------------------------------------------------------