google/latexify_py

Support guard clauses

wd60622 opened this issue · 2 comments

Running in the colab notebook, noticed guard clauses are not supported in the cell rendering. Thought they are common enough, to get support

# works 
@latexify.function
def foo(x): 
    if x > 0: 
        return x
    else: 
        return 0 

foo 


@latexify.function 
def foo(x): 
    if x > 0: 
         return x

    return 0

# raises LatexifyNotSupportedError
foo

version: 0.2.0b2

@wd60622
Thanks for raising the issue!
I think we can (relatively easily) support any functions in which:

  • All guard clauses have only a return statement or another if clause, and
  • All guard clauses are placed after any other statements, i.e., guard clauses can be converted to a pair of if-else.

Additionally, we can support any functions with only if clauses and assignments when reduce_assignments=True.

In the case of reduce_assignments=False (default), we need to consider how the discrepancy of assigned values should be expressed. For example:

def f(x):
    y = a(x)
    if b(x):
        return y
    y = c(x)
    return y

I think this kind of functions are not easily expressed without assignment reduction, and eventually we need the algorithmic form (#57)

Awesome.
Yeah, It doesn't seem too hard of an adaption. Guessing without a guard, the orelse attribute of the ast.If will be the rest of the body in the case with a guard.