Sum of a series: Difference between revisions

Content added Content deleted
(add Fermat)
(→‎{{header|F_Sharp|F#}}: Add proper fp style solution)
Line 848: Line 848:
<lang fsharp>> f 1000. ;;
<lang fsharp>> f 1000. ;;
val it : float = 1.643934567</lang>
val it : float = 1.643934567</lang>
However this recursive function will run out of stack space eventually (try 100000). A [[:Category:Recursion|tail-recursive]] implementation will not consume stack space and can therefore handle much larger ranges. Here is such a version:
However, this recursive function will run out of stack space eventually (try 100000). A [[:Category:Recursion|tail-recursive]] implementation will not consume stack space and can therefore handle much larger ranges. Here is such a version:
<lang fsharp>#light
<lang fsharp>#light
let sum_series (max : float) =
let sum_series (max : float) =
Line 863: Line 863:
0</lang>
0</lang>
This block can be compiled using ''fsc --target exe filename.fs'' or used interactively without the main function.
This block can be compiled using ''fsc --target exe filename.fs'' or used interactively without the main function.

For a much more elegant and FP style of solving this problem, use:
<lang fsharp>
Seq.sum [for x in [1..1000] do 1./(x * x |> float)]
</lang>


=={{header|Factor}}==
=={{header|Factor}}==