-- 1-15-Haskell.hs -- -- Haskell is a functional programming language. -- Variables are immutable, and repetition is commonly -- expressed using recursion rather than loops that -- repeatedly modify variables. -- -- A function definition also often has a separate type -- signature. For example, -- -- mySin :: Double -> Double -- -- says that mySin takes a Double and returns a Double. main :: IO () main = do let x = 3.2 putStrLn $ "mySin x: " ++ show (mySin x) putStrLn $ "sin x: " ++ show (sin x) putStrLn $ "reference: " ++ show (-0.058374143427579909137) putStrLn $ "mySin (1.0/0.0): " ++ show (mySin (1.0/0.0)) -- mySin :: Double -> Double -- -- Approximate sin(x) using the Taylor series -- -- x^3 x^5 x^7 -- sin(x) = x - --- + --- - --- + ... -- 3! 5! 7! -- -- Rather than calculating each power and factorial -- separately, calculate each term from the previous -- term: -- -- x^2 -- next = -term -----------, -- n(n + 1) -- -- where n takes the values 2, 4, 6, ... -- -- Haskell does not modify result, term, and n. -- Instead, each recursive call supplies new values -- for them. mySin :: Double -> Double mySin x | isNaN x || isInfinite x = 0.0/0.0 | otherwise = next x x 2.0 where next result term n = let nextTerm = -term*(x/n)*(x/(n + 1.0)) in if abs nextTerm < 1e-16 then result else next (result + nextTerm) nextTerm (n + 2.0)