DEV Community

Discussion on: Trapezoidal Rule in F#

Collapse
 
bohdanstupak1 profile image
Bohdan Stupak

Great job but I'm not sure why using functional-first language to use it OO-style. To me using mutable in F# is a flag that something is done in a non-functional fashion.
How about considering the code below?

let trapezoidal2 a b N = 
    let h = (b - a)/N
    let initialAccValue = h/2.0*(f(a)+f(b))
    [|1 .. System.Convert.ToInt32(N)|]
    |> Array.mapi(fun i x -> i+1,x)
    |> Array.fold (fun acc (i,_) -> acc + h*f(float(i)*h+a)) initialAccValue     

The key tricks here are Array.mapi which allows us to work with tuple (element,index) instead of just an element; and substitution of iterative increment of xi by h to multiplication index*h+a

Collapse
 
marinesm profile image
Maria Ines Montenegro • Edited

Since this was my first time with a functional programming language I think I hadn't fully grasped the concepts. I ended up using recursion in order to remove the mutable variables; which I updated in my post. Thank you very much for your feedback!