github.com/k14s/starlark-go@v0.0.0-20200720175618-3a5c849cc368/starlark/testdata/recursion.star (about)

     1  # Tests of Starlark recursion and while statement.
     2  
     3  # This is a "chunked" file: each "---" effectively starts a new file.
     4  
     5  # option:recursion
     6  
     7  load("assert.star", "assert")
     8  
     9  def sum(n):
    10  	r = 0
    11  	while n > 0:
    12  		r += n
    13  		n -= 1
    14  	return r
    15  
    16  def fib(n):
    17  	if n <= 1:
    18  		return 1
    19  	return fib(n-1) + fib(n-2)
    20  
    21  def while_break(n):
    22  	r = 0
    23  	while n > 0:
    24  		if n == 5:
    25  			break
    26  		r += n
    27  		n -= 1
    28  	return r
    29  
    30  def while_continue(n):
    31  	r = 0
    32  	while n > 0:
    33  		if n % 2 == 0:
    34  			n -= 1
    35  			continue
    36  		r += n
    37  		n -= 1
    38  	return r
    39  
    40  assert.eq(fib(5), 8)
    41  assert.eq(sum(5), 5+4+3+2+1)
    42  assert.eq(while_break(10), 40)
    43  assert.eq(while_continue(10), 25)