最近我提出了google cloud function的递归和尾部递归的实现方式。这种方式实现了函数式编程方法。
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)
发布于 2019-02-08 00:49:20
云函数仍然只是常规函数,您可以使用它进行递归。您不需要进行重复的HTTP请求,您只需在递归调用函数时为函数提供一个参数,以模拟Cloud函数将注入的参数。
例如,以下是作为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}))
尾递归也是类似的。
发布于 2019-02-08 00:12:39
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 - tail递归函数:
# 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中使用这种递归函数方法实现。
https://stackoverflow.com/questions/54577581
复制相似问题