I was bored, and looking to do something that involved anonymous functions, and it was suggested by @Quill, that I create a summation function. I decided to also include a product function as well to top the whole thing off.
For those who don't know, a summation is usually defined like this:
$$\sum_{n=a}^{b}f(n)$$
And a product is usually defined like this:
$$\prod_{n=a}^{b}f(n)$$
I'd like to know the following things:
- Am I doing this in a proper functional way?
- Is there a way to reduce the repetitiveness of the code?
- Is it okay to use
List.fold
to multiply all the elements of a list together? Is there a better way? - Am I violation any style guidelines?
- Anything else?
Here's the code:
/// <summary>
/// Find the summation in a specific range, given
/// a specific function.
/// </summary>
let summation func low high =
let function_result_set: int list = [for x in low..high do yield x |> func]
let result = function_result_set |> List.sum
result
/// <summary>
/// Find the product in a specific range, given
/// a specific function.
/// </summary>
let product func low high =
let function_result_set: int list = [for x in low..high do yield x |> func]
let result = function_result_set |> List.fold (*) 1
result
And finally, here's a few tests:
[<EntryPoint>] let main argv = System.Console.WriteLine(summation (fun n -> n) 1 10) System.Console.WriteLine(product (fun n -> n) 1 10) System.Console.ReadKey() |> ignore 0
And here's the desired output from the above tests:
55 3628800
1 * 2 * 3 .... 9 * 10
rather than1 + 2 + 3 ... 9 + 10
. \$\endgroup\$