lc: List comprehension

Description Usage Arguments Examples

View source: R/lc.R

Description

This function implements list comprehension, an alternative to Filter and Map for working with lists. The syntax is as follows: lc(expr, lists, predicates) where expr is some expression to be evaluated for all elements in the lists, where lists are one or more named lists, where these are specified by a name and an expression name = list_expr, and where predicates are expressions that should evaluated to a boolean value. For example, to get a list of all even numbers, squared, from a list x we can write lc(x ** 2, x = x, x %% 2 == 0). The result of a call to lc is a list constructed from the expressions in expr, for all elements in the input lists where the predicates evaluate to true.

Usage

1
lc(expr, ...)

Arguments

expr

An expression that will be evaluated for each element in the input lists.

...

Additional list or predicate arguments.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
qsort <- function(lst) {
    n <- length(lst)
    if (n < 2) return(lst)
    pivot <- lst[[sample(n, size = 1)]]
    smaller <- lc(x, x = lst, x < pivot)
    equal <- lc(x, x = lst, x == pivot)
    larger <- lc(x, x = lst, x > pivot)
    c(qsort(smaller), equal, qsort(larger))
}
(lst <- sample(1:10))
unlist(qsort(lst))

mailund/lc documentation built on May 29, 2019, 6:53 p.m.