我如何表达阶乘n!与F#函数,递归或其他? [英] How can I express a factorial n! with an F# function, recursive or otherwise?

查看:76
本文介绍了我如何表达阶乘n!与F#函数,递归或其他?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自然数的阶乘(大于或等于0的任何数字)是该数字乘以自身的阶乘减去一,其中0的阶乘定义为1.

A factorial of a natural number (any number greater or equal than 0) is that number multiplied by the factorial of itself minus one, where the factorial of 0 is defined as 1.

例如:

0! = 1
1! = 1 * 0!
2! = 2 * 1!
3! = 3 * 2!
4! = 4 * 3!
5! = 5 * 4!

另一种写法是将1n之间的所有自然数乘以n!:

Another way of writing this is to multiply all natural numbers between 1 and n for n!:

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

我该如何用F#中的递归函数表达这一点?而应该我要使用递归函数吗?

How can I express this with a recursive function in F#? And should I do it with a recursive function?

//Factorials!
let factorial n = 
    result = ?

推荐答案

操作方法,选项1:

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

方法,选项2(尾递归,编译成循环):

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:

在F#中进行尾部或尾部递归时,如何使用何时?

我主张经常避免使用迭代和递归来支持高阶函数.但是,如果您才刚刚起步,也许不必太担心该建议. (但请参见例如@ChaosPandion的答案,或例如

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

这篇关于我如何表达阶乘n!与F#函数,递归或其他?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆