14  Lazy Evaluation

14.1 Lazy evaluation

Code
fn_mean = function(x, y, ...) {
    fn_n = function(x, na.rm = FALSE) ifelse(na.rm, length(na.omit(x)), length(x))
    xn = fn_n(x, ...)
    xsum = sum(x, ...)
    xmean = xsum/xn
    return(xmean)
}

14.2 Data

Code
A = c(NA, 12, 15, 14, 18)

14.3 Lazy evaluation of function: Call 1

Code
fn_mean(A, na.rm = TRUE)
[1] 14.75

14.4 Lazy evaluation of function: Call 2

Code
fn_mean(A, y = 5, na.rm = TRUE)
[1] 14.75

14.5 Lazy evaluation

Code
def fn_mean(x, na_rm=False, y=None):
    
    if na_rm:
        x = x[~np.isnan(x)]
    
    xn = len(x)
    xsum = np.sum(x)
    
    xmean = xsum / xn 
    return xmean

# Example usage:
A = np.array([11, 12, np.nan, 14, 15])
fn_mean(A, na_rm=True)
fn_mean(A, na_rm=True, y=5)