A factorial is a number that multiplies itself and minus one and so on and so forth until it reaches zero.

For example !5! = 5 * 4 * 3 * 2 * 1

How would I declare a recursive function for this? *Should* I declare a recursive function for this? Thanks for the help.

```
//Factorials!
let factorial n =
result = ?
```

How, option 1:

```
let rec factorial n =
match n with
| 0 | 1 -> 1
| _ -> n * factorial(n-1)
```

How, option 2 (tail recursive, compiled into a loop):

```
let factorial n =
let rec loop i acc =
match i with
| 0 | 1 -> acc
| _ -> loop (i-1) (acc * i)
loop n 1
```

Should: no, see my answer to:

While or Tail Recursion in F#, what to use when?

where I advocate often avoiding both iteration and recursion in favor of higher-order functions. But if you're just getting started, maybe don't worry too much about that advice yet. (But then see e.g. @ChaosPandion's answer, or e.g.

```
let factorial n = [1..n] |> List.fold (*) 1
```

Or even:

```
let factorial n = [1..n] |> List.reduce (*) // doesn't require the 2nd parameter
```

How would I declare a recursive function for this?

First of all, to define a recursive function, you'd use `let rec`

instead of `let`

(because `let`

does not allow you to refer to the function you're defining recursively).

To define the factorial function recursively, the easiest (but not most efficient) way would be to use the standard mathematical definition of the factorial function.

A more efficient approach would be to define a tail-recursive helper function taking a second argument which stores the result calculated thus far.

Here is another example:

```
let factorial (num:int) =
seq { for n in [1..num] -> n }
|> Seq.reduce (fun acc n -> acc * n)
```

This example might be a bit clearer:

```
let factorial num =
[1..num] |> Seq.fold (fun acc n -> acc * n) 1
```

Brian's answers are most practical, but here is the solution in continuation passing style:

```
let rec factorial n =
let rec loopk i k =
match i with
| 0 | 1 -> k i
| _ -> loopk (i-1) (fun r -> k (i * r))
in loopk n (fun r -> r)
```

My favorite F# solution to recursive sequences is... infinite, tail-recursive sequences!:

```
let factSeq =
let rec factSeq m n =
seq { let m = m * n
yield m
yield! factSeq m (n+1I) }
seq { yield 1I ; yield 2I ; yield! (factSeq 2I 3I) }
let factTake n = factSeq |> Seq.take n //the first n terms
let fact n = factSeq |> Seq.nth (n-1) //the nth term
```

I'm using BigIntegers here since the factorial sequence grows so quickly (go ahead, try the 20,000th term).

I generally agree with Brian's advice to use higher-order functions over iterative loops or recursive loops (tail-recursion + accumulator) whenever possible. But I think in this case, an infinite sequence as I've shown is more flexible since it produces all terms of the factorial sequence up to the desired term (`factTake`

), and each term only requires only one multiplication step (n*(n-1)). Whereas, if you wanted the first n terms using a fold solution, each calculation would be done independently and wouldn't benefit from the previous calculation.

Here is a simpler implementation

```
let rec bfact (n):bigint =
match n with
| i when i<0 -> bigint.Zero
| 0 | 1 -> bigint(1)
| _ -> ( bfact(n-1) * bigint(n) )
```

And to test

```
bfact(50)
val bfact : n:int -> bigint
val it : bigint =
30414093201713378043612608166064768844377641568960512000000000000
```

Similar Questions

I have written a large module in F# that happens to have a trivial interface. The module contains about 1000 lines of code, 50 unit tests, and exports just one easily understood function. The natural

say there is a function to calculate factorial(n) Does factorial(7) creates 7 function object for each of n from 1 to 7 and use those values when ever necessary (for factorial(8) as like factorial(7)*

How can i make a SQL query from actionscript? and render all the results

A while back I wrote a function to fill time series matrices that had NA values up according to the specifications needed and it's had occational uses on a few matrices that are about 50000 rows, 350

I cannot use AsEnumerable() on DataTable, I'm using C# 3 but I'm just targeting 2.0 framework (LINQ capability is courtesy of LINQBridge). Is there any way I can make DataTable enumerable without usin

How can I make Impromptu jquery pause current-function execution like Javascript's native alert function ? http://trentrichardson.com/Impromptu/ Currently script execution continues in the backgroun

how can i make payment using this URL https://api-3t.sandbox.paypal.com/nvp and is there any difference making request from this URL https://svcs.sandbox.paypal.com/AdaptivePayments and this URL https

I am hoping there is a library function somewhere that can do this. And yes it is very important that it be the factorial of a double value (that is it needs to work with non-integer values).

I currently have this watermark to print a text on my photos. The sad thing is that I can't use it on my personal website, because it drains too much memory from PHP. My question is now how I can make

I would like to know how to make a C-function and be able to tell Lua about it, then call it from Lua. I have all the Lua Libraries installed on my Mac OSX 10.4 computer.

I can't figure out a discrepancy between the time it takes for the Contains method to find an element in an ArrayList and the time it takes for a small function that I wrote to do the same thing. The

I've been trying out Coda for the Mac. I really like it, except for one thing. It does no auto indention between brackets. I'm use to having other editors I use to automatically close brackets and tab

I want to compress a list in Python in the rule below: ['a', 'a', 'a', 'b', 'b', 'c'] -> [3, 2, 1] I want to use the built-in map/reduce function in Python, how to make it? Thanks!

I'd like to unit test fun1 without calling fun2. let fun2() = // Some complex function with lots of dependencies. 1 let fun1() = fun2() * 2 What the best way to break the dependency between the two f

I found this useful library jQuery.Keyframes to help me use CSS keyframes using Jquery to work on IE , but it seems it can only take CSS styles at each different percentages , How can I make it execut

I would like to solve the following quadratic programming equation using ipop function from kernlab : min 0.5*x'*H*x + f'*x subject to: A*x <= b Aeq*x = beq LB <= x <= UB where in our examp

I have this function which I define and as soon as it is defined I execute it. Is there a way I can combine the definition and the execution in one go as this is the only place this function is used?

I am new to this website; in fact this is my first question. So if I am asking this question in the wrong context, please inform me so I can make the adjustments. I have a program that is created in V

I want to make my SDL program sound a simple beep at a certain frequency. How do I go about doing that? I've found a tutorial that writes to SDL's sound buffer or so, but it doesn't seem to work. (I'm

everytime I try to get the factorial of 171, I get INF. 170 works fine. Is it possible to get the factorial of 171+ in a script? How? My function: function factorial($n) { if ($n == 0) return 1; retur

can you please help me?, i can't explain my question clearly, I define x & y ,i can write plot(f(end,y)) ,but I want to know that how can i must type this code for f(first,y)?thank you!

If a dll exports some functions and the functions have only ordinal numbers, how can I call the functions? Give me a short example please.

I am using Accord.NET in F# for the first time and I am having problems creating the function to calculate the distance for KNN. Here is my code static member RunKNN = let inputs = MachineLearningEngi

I'm trying to solve $\sum_{j=1}^{180} x^{a_j} = 1$ I created two functions : f1 <- function(x){c(rep(x,180))} f2 <- function(x){sum(f1(x)^vec) - 1} where vec is my $a_j$ vector. Uniroot doe

So consider the following program-segment! I've tried to use the basic recursion function to determine the factorial of a number, but now using the BigInteger class. public static BigInteger fact(int

This question already has an answer here: How can I make a UIButton get a function when I touch outside the button and drag over the button? 2 answers Is there any event for this dragging from

How can I make cookies in my Flash application using ActionScript 2.0?

I need the same function like the Typo3 standard. There U can Choose a Link (external Site, internal Site, File, etc.) How can I make this?

I want to make my browser full screen. Same as when we do F11 key event. I found some examples such as function maxwin() { var wscript = new ActiveXObject(WScript.Shell); if (wscript!=null) { wscri

I'm using knockout.js. I have several editable grids in a form, and the names of the fields inside those grids matter, so using uniqueName isn't an option. So what I'm doing is calling a function to r

I'm wondering if my algorithm is tail recursive; I've just made this function to pretty print an array in PHP: function get_pretty_output($value, $first=true, $indent = ''){ if (!is_array($value)) {

I've got a folder in linux, which is contained several shared object files (*.so). How I can find function in shared object files using objdump and bash functions in linux? For instance, the following

How can I make shwOpts.show(fast); to act when removeHighlight() is done? I thought if I put an anonymous function as an argument in the other it will act as a callback. This didn't work. removeHigh

I've disabled X button in Qt from my dialog using this line: myDialog->setWindowFlags(Qt::Dialog | Qt::Desktop) but I couldn't detect Alt + F4 using this code: void myClass::keyPressEvent(QKeyEve

This is absolutely driving me nuts. The supposed simplest thing I can imagine and I can't do it. I just want to computer factorial inputting an int and output a real. I've tried to coerce in numerous

How to compute the factorial using Scala actors ? And would it prove more time efficient compared to for instance def factorial(n: Int): BigInt = (BigInt(1) to BigInt(n)).par.product Many Thanks.

my question is not so much about code as it is the logic behind writing a factorial program. I am currently taking a MOOC at the University of Helsinki and I have become stuck on this exercise. As the

I am trying to unset function using be searching for all of them and then looping to unset them with no luck Non loop way works (example where bar_ is created and unset) function bar_ { echo bar; }

I have seen* something where a certain key can be called both as a variable and as a function. The variable would return a value, the function would do something functiony. obj.test // E.g. 16 obj.tes

I tried to get the cube root in F#. But here is my problem. let x5 = ((float 64) ** (1.0/3.0));; val x5 : float = 4.0 int x5;; //expected 4 val it : int = 3 The result should be 4, not 3. What's wron

I am using VS Team System 2008 version 9.0.21022.8 RTM, .NET Framework 3.5 SP1. I get C# and VB.NET Intellisense, but not for F# May 2009 CTP. UPDATE July 7th, 2009 I am installing VS 2008 SP1, maybe

How can i change the /api in my routing to make it configurable for my customer without editing the routing.yml ? api_entry: path: /api/{method} defaults: { _controller: WarrenApiBundle:Api:method }

I'm having a logic problem here. I want to add the result of the factorial values but I'm not sure how to add them. Here's my code: using System; using System.Collections.Generic; using System.Linq; u

So I have a function that takes four numerical arguments and produces a numerical argument. f(w,x,y,z) --> A If I have the function f and a target result A, is there an iterative method for disco

I would like to make so file in order to use it in python. how can I make shared library from fortran source? I have tested like below code. gfortran -c mod.f90 #gfortran -c sub1.f90 gfortran -c func.

In my free time I like polishing my algorithm / programming skills (well, my skills suck and I try to improve them) by solving problems on pages like topcoder.com or uva.onlinejudge.com. Usually I can

I would like to valid a string if it consists of M or F. If possible i would also like to know if some one enters Male or Female i would like to get the result as M or F.. But my first case is to chec

How Do I profile my functions using DrScheme? (require profile) (define (factorial n) (cond ((= n 1) 1) (else (* n (factorial (- n 1)))))) (profile factorial) The above code returns Profiling result

How can I make my following code DRY (Dont Repeat Yourself) - (void)updateLetterScore { // NOT DRY... Must fix if (percentScore < 60.0) letterLabel.text = [NSString stringWithFormat:@F]; if (pe

I need to compute the rising factorial of big numbers, the best I found until now is the rising factorial function from the sympy package sympy package, that is really nice, but I would still need som