google / latexify_py

A library to generate LaTeX expression from Python code.
Apache License 2.0
7.16k stars 380 forks source link

Support guard clauses #100

Open wd60622 opened 1 year ago

wd60622 commented 1 year ago

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

odashi commented 1 year ago

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

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)

wd60622 commented 1 year ago

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.