F # Function assignment
If you want a recursive form without using match
, use normal conditional code:
let rec Sum n =
if n = 0 then 0 else n + Sum (n-1)
An idiomatic way to emulate Haskell would be:
let rec Sum = function
| 0 -> 0
| n -> n + Sum (n-1)
But you don't really need recursion, since there is a closed form; see the "too obvious" part of @bytebuster's code.
source to share
The following code is incorrect because it contains a double definition Sum
. F # syntax is different from Haskell and requires a separate write of a branching function to be executed internally using match
or chaining if
.
Also, this code is not very accurate because it ends up in an infinite loop if a negative argument is received.
There are several easy ways to do what you need without match
. Note that they also require checking the range of the arguments:
let Sum1 x = x * (x+1) / 2 // too obvious
let Sum2 x = Seq.init id |> Seq.take (x+1) |> Seq.sum
source to share