github.com/lab47/exprcore@v0.0.0-20210525052339-fb7d6bd9331e/exprcore/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  	}
    15  	return r
    16  }
    17  def fib(n) {
    18  	if n <= 1 {
    19  		return 1
    20  	}
    21  	return fib(n-1) + fib(n-2)
    22  }
    23  def while_break(n) {
    24  	r = 0
    25  	while n > 0 {
    26  		if n == 5 {
    27  			break
    28  		}
    29  		r += n
    30  		n -= 1
    31  	}
    32  	return r
    33  }
    34  def while_continue(n) {
    35  	r = 0
    36  	while n > 0 {
    37  		if n % 2 == 0 {
    38  			n -= 1
    39  			continue
    40  		}
    41  		r += n
    42  		n -= 1
    43  	}
    44  	return r
    45  }
    46  assert.eq(fib(5), 8)
    47  assert.eq(sum(5), 5+4+3+2+1)
    48  assert.eq(while_break(10), 40)
    49  assert.eq(while_continue(10), 25)