The proper title of this question should be "Summations and products, and factorials oh my!".
After getting quite a bit of useful feedback on this question from @mjolka, and a comment, I decided that there were many things to be improved.
These are the following things that I've added/changed:
- A
factorial
function which uses theproduct
function. - Support for getting the sum, and product of sequences with no elements.
- Strongly typed anonymous function parameters.
Again, for those who don't know, a summation is defined as follows:
$$\sum_{n=a}^{b}f(n)$$
And a product is defined as follows:
$$\prod_{n=a}^{b}f(n)$$
I'd like to know the following things, which are more or less mostly the same as the ones in the last question:
- Am I writing this in a proper functional way?
- How can I reduce the repetitiveness in my code?
- Is there a way to improve performance? It already runs pretty fast, at approximately \$0.025\$ seconds for inputs of \$10\$).
- Anything else?
Here's the code:
let inline summation (f: (double -> double)) low high =
match (low, high) with
| (low, high) when low <> high ->
{ low .. high }
|> Seq.map f
|> Seq.sum
| (low, high) when low = high -> 0.0
| _ -> -1.0
let inline product (f: (double -> double)) low high =
match (low, high) with
| (low, high) when low <> high ->
{ low .. high }
|> Seq.map f
|> Seq.fold Checked.op_Multiply 1.0
| (low, high) when low = high -> 1.0
| _ -> -1.0
let inline factorial n =
product (fun x -> x) 1.0 n
Here's a few small tests to ensure that the code works:
[<EntryPoint>] let main argv = System.Console.WriteLine(summation (fun x -> x) 1.0 10.0) System.Console.WriteLine(product (fun x -> x) 1.0 10.0) System.Console.WriteLine(factorial 10.0) 0
And here's expected output of the above tests:
55 3628800 3628800