Skip to content

Instantly share code, notes, and snippets.

@surganov
Created August 23, 2014 19:26

Revisions

  1. surganov created this gist Aug 23, 2014.
    32 changes: 32 additions & 0 deletions 1-29.hs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    cube :: Float -> Float
    cube x = x * x * x

    sum' :: (Float -> Float) -> Float -> (Float -> Float) -> Float -> Float
    sum' term a next b =
    if a > b
    then 0
    else term a + sum' term (next a) next b

    integral :: (Float -> Float) -> Float -> Float -> Float -> Float
    integral f a b n = (h / 3) * (sum' term 0 (+1) n) where
    h = (b - a) / n
    y k = f $ a + k * h
    term k
    | k == 0 || k == n = y k
    | odd k = 4 * y k
    | even k = 2 * y k

    main = do
    print $ integral cube 0 1 100

    -- No instance for (Integral Float) arising from a use of `odd'
    -- Possible fix: add an instance declaration for (Integral Float)
    -- In the expression: odd k
    -- In a stmt of a pattern guard for
    -- an equation for `term':
    -- odd k
    -- In an equation for `term':
    -- term k
    -- | k == 0 || k == n = y k
    -- | odd k = 4 * y k
    -- | even k = 2 * y k