{- -------------------- Math-oriented examples in Haskell from the Hugs distribuion library (probably due to Mark Jones or Alastair Reid) -------------------- -} module MathEgs where import Gofer -------------------- -- Perfect numbers factors n = [ i | i<-[1..n-1], n `mod` i == 0 ] perfect n = sum (factors n) == n firstperfect = head perfects perfects = filter perfect [(1::Int)..] -------------------- -- Prime numbers primes :: Integral a => [a] primes = map head (iterate sieve [2..]) sieve (p:xs) = [ x | x<-xs, x `rem` p /= 0 ] -------------------- -- Pythagorean triads triads n = [ (x,y,z) | let ns=[1..n], x<-ns, y<-ns, z<-ns, x*x+y*y==z*z ] -------------------- -- Pascal's triangle pascal :: [[Int]] pascal = iterate (\row -> zipWith (+) ([0]++row) (row++[0])) [1] showPascal = putStr ((layn . map show . take 14) pascal) -------------------- -- Digits of e eFactBase :: [Int] eFactBase = map head (iterate scale (2:repeat 1)) scale :: Integral a => [a] -> [a] scale = renorm . map (10*) . tail renorm ds = foldr step [0] (zip ds [2..]) step (d,n) bs | (d `mod` n + 9) < n = (d `div` n) : b : tail bs | otherwise = c : b : tail bs where b' = head bs b = (d+b') `mod` n c = (d+b') `div` n