Although the list fields of each member are directly accessible in the expression, sometimes we still need to access the list member itself, usually for its meta-information. Lambda expressions provide a mechanism that allows you to use default or customized meta-symbols to access the meta-information of the list member.
In rlist package, all functions that work with expressions support the following types of lambda expressions.
x -> expression
f(x) -> expression
f(x,i) -> expression
f(x,i,name) -> expression
Implicit lambda expression is an ordinary expression with no special syntax like ~
or ->
. In this case, meta symbols are implicitly defined in default, that is, .
represents the list member, .i
represents the index, and .name
represents the name of the list member.
For example,
x <- list(a=list(x=1,y=2),b=list(x=2,y=3))
list.map(x,y)
# $a
# [1] 2
#
# $b
# [1] 3
list.map(x,sum(as.numeric(.)))
# $a
# [1] 3
#
# $b
# [1] 5
In the second mapping above, .
represents each list member. For the first member, the meta-symbols take the following values:
. = x[[1]] = list(x=1,y=2)
.i = 1
.name = "a"
To use other symbols to represent the metadata of a list member, we can use explicit lambda expressions.
x <- list(a=list(x=1,y=2),b=list(x=2,y=3))
list.map(x, f(item,index) -> unlist(item) * index)
# $a
# x y
# 1 2
#
# $b
# x y
# 4 6
list.map(x, f(item,index,name) -> list(name=name,sum=sum(unlist(item))))
# $a
# $a$name
# [1] "a"
#
# $a$sum
# [1] 3
#
#
# $b
# $b$name
# [1] "b"
#
# $b$sum
# [1] 5
For unnamed vector members, it is almost necessary to use lambda expressions.
x <- list(a=c(1,2),b=c(3,4))
list.map(x,sum(.))
# $a
# [1] 3
#
# $b
# [1] 7
list.map(x,item -> sum(item))
# $a
# [1] 3
#
# $b
# [1] 7
list.map(x,f(m,i) -> m+i)
# $a
# [1] 2 3
#
# $b
# [1] 5 6
For named vector members, their name can also be directly used in the expression.
x <- list(a=c(x=1,y=2),b=c(x=3,y=4))
list.map(x,sum(y))
# $a
# [1] 2
#
# $b
# [1] 4
list.map(x,x*y)
# $a
# [1] 2
#
# $b
# [1] 12
list.map(x,.i)
# $a
# [1] 1
#
# $b
# [1] 2
list.map(x,x+.i)
# $a
# [1] 2
#
# $b
# [1] 5
list.map(x,f(.,i) -> . + i)
# $a
# x y
# 2 3
#
# $b
# x y
# 5 6
list.map(x,.name)
# $a
# [1] "a"
#
# $b
# [1] "b"