F # Function assignment

Is there a way in F # to define a function that gives the sum of all natural numbers up to a given integer parameter without using a construct match


In other words, why is the following code wrong?

let Sum 0 = 0
let Sum n = n + Sum (n - 1)



source to share

2 answers

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.



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




All Articles