Help me please. I am a complete newcomer to HASKEL, I teach him less than a week.

There is a task:

“Implement a function that finds the value of a definite integral of a given function f on a given interval [a, b] by the trapezium method. (Use a uniform grid; 1000 elementary segments are enough.)

integration :: (Double -> Double) -> Double -> Double -> Double integration fab = undefined GHCi> integration sin pi 0 -2.0 

The result may differ from -2.0, but not more than 1e-4. "

My code is:

 integration fab | a < b = helper fab 0 ( (b - a) / 1000) | otherwise = -1 * integration fba helper fab res step | (abs (b - a)) < step = res + ( ((fa + fb) / 2) * abs (a - b) ) | otherwise = helper f (a + step) b (res + ( ( (fa) + (f (a + step))) / 2 ) * step ) step 

(It's a little bit wrong, but for some reason, not everything fits here.)

Falls on the first test: out of memory. Kill though I do not understand what was done wrong. What to change? How to improve?

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • I do not know why your function does not work, so I will throw my decision in the comment (after all, this is not a direct answer to your question): pastebin.com/r6WUjR0R . - Daniel Kolesnichenko

2 answers 2

I tried your code. Compiled GHC 7.10.1. Error failed to repeat. Nevertheless, I would venture to suggest that an error may occur.

In the case of out of memory, it is most logical to assume that the condition for stopping the function is not fulfilled and it falls into infinite recursion (or cycle). This results in either a stack overflow or the completion of available memory.

In the helper function, the completion condition is (abs (b - a)) < step . Try to remove the abs function from the condition and the expression res + ( ((fa + fb) / 2) * abs (a - b) ) also rewrite without abs: res + ( ((fa + fb) / 2) * (b - a) )

     integration fab | a < b = helper ... | otherwise = -1 * integration fba 

    What happens when a == b? (In this example, the cause of the hang is different)