---
# System prepended metadata

title: GTScript Loop Syntax
tags: [Felix’s remains]

---

# GTScript Loop Syntax

###### tags: `Felix’s remains`

## Current Style

Big disadvantage: this can not be implemented in a pure Python backend (that is, without parsing and analysing the AST).

```python=
@stencil(order=FORWARD)
def forward(a, b, c, d):
    with interval(0, 1):
        cp = c / b
        dp = d / b
    with interval(1, None):
        cp = c / (b - a * cp[K - 1])
        dp = (d - a * dp[K - 1]) / (b - a * cp[K - 1])
    return cp, dp    
```

## Generator Style

```python=
@stencil
def forward(a, b, c, d):
    for k in krange[:1]:
        cp = c[k] / b[k]
        dp = d[k] / b[k]
        yield k, cp, dp
    for k in krange[1:]:
        cp = c[k] / (b[k] - a[k] * cp)
        dp = (d[k] - a[k] * dp) / (b[k] - a[k] * cp)
        yield k, cp, dp
```

## Single-Column Abstraction

```python=
@stencil
def forward(a, b, c, d):
    cp = column()
    dp = column()
    for k in krange[:1]:
        cp[k] = c[k] / b[k]
        dp[k] = d[k] / b[k]
    for k in krange[1:]:
        cp[k] = c[k] / (b[k] - a[k] * cp[k - 1])
        dp[k] = (d[k] - a[k] * dp[k - 1]) / (b[k] - a[k] * cp[k - 1])
    return cp, dp 
```

```python=
@stencil
def forward(a, b, c, d):
    cp = column()
    dp = column()
    for k in krange():
        if k == 0:
            cp[k] = c[k] / b[k]
            dp[k] = d[k] / b[k]
        else:
            cp[k] = c[k] / (b[k] - a[k] * cp[k - 1])
            dp[k] = (d[k] - a[k] * dp[k - 1]) / (b[k] - a[k] * cp[k - 1])
    return cp, dp 
```

## Object Style

It is basically a functor with the state.
It's call represents the procesing of a single k-layer.

```python=
class Forward:

    def __call__(self, k, a, b, c, d): 
        if k == 0:
            self.cp = c / b
            self.dp = d / b
        else:
            self.cp = c / (b - a * self.cp)
            self.dp = (d - a * self.dp) / (b - a * self.cp)
        return self.cp, self.dp 
```

`class` boilerplate can be packed into decorator together with the scan direction 

```python=

@scan_stencil(dir=FORWARD)
def forward(state, k, a, b, c, d): 
    if k == 0:
        state.cp = c / b
        state.dp = d / b
    else:
        state.cp = c / (b - a * state.cp)
        state.dp = (d - a * state.dp) / (b - a * state.cp)
    return state.cp, state.dp 
```
