RobinHankin / mvp

https://robinhankin.github.io/mvp/
8 stars 3 forks source link

Reduce() #35

Open RobinHankin opened 5 years ago

RobinHankin commented 5 years ago
 f <- function(x){1+Reduce(function(u, v) {u*(1+v)}, x, right = TRUE)}
 f(list(as.mvp("a"),as.mvp("b"),as.mvp("c"),as.mvp("d")))
mvp object algebraically equal to
1  +  a  +  a b  +  a b c  +  a b c d
> 
RobinHankin commented 5 years ago

Perhaps the function should take a list, in which case:

 g <- function(...){1 + Reduce(function(u, v) {u*(1+v)}, list(...), right = TRUE)}
 do.call("g",lapply(letters,function(x){as.mvp(x)}))
mvp object algebraically equal to
1  +  a  +  a b  +  a b c  +  a b c d  +  a b c d e  +  a b c d e f  +  a b c d e f g  +  a b c d e f g h  +  a b c d e f g h i  +  a b c d e f g h i j  +  a b c d e f g h i j k  +  a b c d e f g h i j k l  +  a b c d e f g h i j k l m  +  a b c d e f g h i j k l m n  +  a b c d e f g h i j k l m n o  +  a b c d e f g h i j k l m n o p  +  a b c d e f g h i j k l m n o p q  +  a b c d e f g h i j k l m n o p q r  +  a b c d e f g h i j k l m n o p q r s  +  a b c d e f g h i j k l m n o p q r s t  +  a b c d e f g h i j k l m n o p q r s t u  +  a b c d e f g h i j k l m n o p q r s t u v  +  a b c d e f g h i j k l m n o p q r s t u v w  +  a b c d e f g h i j k l m n o p q r s t u v w x  +  a b c d e f g h i j k l m n o p q r s t u v w x y  +  a b c d e f g h i j k l m n o p q r s t u v w x y z
RobinHankin commented 5 years ago

If we have

thing <- function(symbols){
do.call(function(...){1 + Reduce(function(u, v) {u*(1+v)}, list(...), right=TRUE)},lapply(symbols,function(x){as.mvp(x)}))
}

then we can do wonderful things like:

 thing(sample(letters[1:3],15,replace=TRUE))
mvp object algebraically equal to
1  +  a b  +  a b c  +  a^2 b c  +  a^2 b c^2  +  a^3 b c^2  +  a^3 b^2 c^2  +  a^3 b^2 c^3  +  a^3 b^2 c^4  +  a^3 b^3 c^4  +  a^3 b^4 c^4  +  a^3 b^5 c^4  +  a^3 b^6 c^4  +  a^4 b^6 c^4  +  a^5 b^6 c^4  +  b
> 

and who could resist this:

thing(state.name)