简体   繁体   中英

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM