ax1mx2
ax1mx2

Reputation: 704

F# Function Matching

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

In other words, why is the following code wrong?

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

Upvotes: 3

Views: 98

Answers (2)

Søren Debois
Søren Debois

Reputation: 5688

If you specifically want the recursive form without using match, just use a regular conditional:

let rec Sum n = 
  if n = 0 then 0 else n + Sum (n-1)

The idiomatic way to emulate Haskell would be:

let rec Sum = function
| 0 -> 0
| n -> n + Sum (n-1)

But you actually don't need recursion since there is a closed form; see the "too obvious" part of @bytebuster's code.

Upvotes: 4

Be Brave Be Like Ukraine
Be Brave Be Like Ukraine

Reputation: 7735

The following code is wrong because it contains a double definition of Sum. F# syntax is different to Haskell's and it requires a single function entry with branching done inside, using match or a chain of if's.

Also, such code is not very accurate because it falls into an infinite loop if received a negative argument.

There are several simple ways to do what you need without match. Note, they also require argument range check:

let Sum1 x = x * (x+1) / 2   // too obvious
let Sum2 x = Seq.init id |> Seq.take (x+1) |> Seq.sum

Upvotes: 1

Related Questions