最近我拿出来与执行递归和尾递归的方式谷歌的云功能。通过这种方式实现功能的编程方法。
简单的递归函数在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)
云功能仍然只是普通的功能,你可以用递归。你不需要做重复的HTTP请求,你只需要提供一个参数,当你把它称为递归模仿的论点,即云功能将注入的功能。
举例来说,这里是你的第一个例子作为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}))
尾递归是相似的。
谷歌云功能 - 递归函数:
# 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!'
谷歌云功能 - 尾递归函数:
# 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!'
有不同的场景中,我们可以使用云功能这个递归函数的方法实现!