latexify_py icon indicating copy to clipboard operation
latexify_py copied to clipboard

Support guard clauses

Open wd60622 opened this issue 1 year ago • 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 avatar Nov 13 '22 21:11 wd60622

@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)

odashi avatar Nov 13 '22 23:11 odashi

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.

wd60622 avatar Nov 14 '22 01:11 wd60622