Reputation: 9
I'm giving Haskell a go at the moment and struggling to rewrite loops in terms of recursions.
I am trying to write a basic integrator which takes some function f(x) and integrates it over the range [a, b] via the Midpoint Method. The integrating function takes three parameters N, a, and b, where N is the number of rectangles being used to approximate the integral.
When I try to compile this with GHCI I get a lot of abstract error messages and I don't really know where to start. Lots of 'Out of Scopes' and several 'Multiple Declarations of Main.a [or b]'.
Thanks
MPInt 1 a b = DELTA 1 -- Base case
MPInt N a b = (MPInt (N-1) a b) + DELTA
where
dX = (b - a) / N
DELTA = dX * f (a + dX * (N+0.5))
f :: (Num a) => a -> a
f x = x^2
Upvotes: 1
Views: 617
Reputation: 57590
You've named your function MPInt
. Only the names of modules, classes, types, and constructors can begin with capital letters; values (including functions) must begin with lowercase letters (or an underscore, or certain punctuation marks). The same problem also applies to N
and DELTA
.
You use DELTA
in the definition of the first case of MPInt
, yet it's defined as part of the second case. A where
clause only applies to the expression immediately before it (in this case, the MPInt N a b = ...
definition). (Also, this first use of DELTA
treats it as a function, yet the second use and its definition have it as a numeric value).
Upvotes: 10