如何使用函数式编程方法实现Google Cloud Function?

时间:2019-02-07 16:12:39

标签: python-3.x google-cloud-platform google-cloud-functions tail-recursion

最近,我想出了具有递归和尾递归实现方式的google cloud函数。这种方式实现了函数式编程方法。

Python中的简单递归函数:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

Python中的简单尾递归函数:

def factorial(n, acc=1):
    if n == 0:
        return 1
    else:
        return factorial(n-1, acc*n)

2 个答案:

答案 0 :(得分:1)

Cloud Functions仍然只是常规函数,您可以使用它们进行递归。您无需进行重复的HTTP请求,只需在递归调用该函数时为该函数提供一个参数即可,以模仿Cloud Functions将注入的参数。

例如,这是您的第一个示例作为HTTP触发器:

class MockRequest:
    def __init__(self, args):
        self.args = args

def factorial(request):
    n = request.args.get('n')
    if n == 0:
        return 1
    else:
        return n * factorial(MockRequest({'n': n-1}))

尾部递归将是类似的。

答案 1 :(得分:-1)

Google Cloud Function-递归函数:

# import request
import urllib.request as req

def recursive(request):
    url = "https://<google-cloud-function-domain-url>/function-rec"
    # check the url arg `n` 
    if request.args and 'n' in request.args:
        n = int(request.args.get('n'))
        if n <= 0:
            return str(0)
        else:
            complete_url = url + "?n=" + str(n-1)
            n_1_result = req.urlopen(complete_url).read()
            return str(n + int(n_1_result))
    else:
        return f'Please send the `n` value in the argument!'

Google Cloud Function-尾递归函数:

# import redirect
from flask import redirect

def recursive(request):
    url = "https://<google-cloud-function-domain-url>/function-rec-redirect"
    # check the url arg `n` and `acc` else if with `n` arg
    if request.args and 'n' in request.args and 'acc' in request.args:
        n = int(request.args.get('n'))
        acc = int(request.args.get('acc'))
        if n <= 0:
            return str(acc)
        else:
            complete_url = url + "?n=" + str(n-1) + "&acc=" + str(n + acc)
            return redirect(complete_url, code=307)
    elif request.args and 'n' in request.args:
        n = int(request.args.get('n'))
        if n <= 0:
            return str(0)
        else:
            complete_url = url + "?n=" + str(n-1) + "&acc=" + str(n)
            return redirect(complete_url, code=307)
    else:
        return f'Please send the `n` value in the argument!'

在不同的情况下,我们可以在Cloud Function中使用此递归功能方法实现。!