dkahle / mpoly

Symbolic computing with multivariate polynomials in R
https://dkahle.github.io/mpoly/
12 stars 12 forks source link

Differences in print #3

Closed sommars closed 8 years ago

sommars commented 8 years ago

I want to convert mpolys to strings that are readable by Macaulay2. However, when I run print on a list with more than one element, it gives a different result than when I run print on a list with just one element.

> lapply(mp(c("x+y","x-y")),print,stars=TRUE)
x  +  y
x  -  y
[[1]]
[1] "x  +  y"

[[2]]
[1] "x  -  y"

> lapply(mp(c("x+y")),print,stars=TRUE)
   x coef 
   1    1 
   y coef 
   1    1 
[[1]]
   x coef 
   1    1 

[[2]]
   y coef 
   1    1 

For me, it would be best if the single element case worked the same way as the multi element case. If there's a reason that print works this way, I can always code around it.

dkahle commented 8 years ago

The problem is that they are different kinds of objects:

library(mpoly)

p <- mp("x + y")
ps <- mp(c("x + y", "x - y"))

class(p)
class(ps)

is.mpoly(p)
is.mpolyList(p)

is.mpoly(ps)
is.mpolyList(ps)

I'd do this: first test the object then do the printing. If it's an mpoly object, either print it or mpolyList it to convert it to an mpolyList.

str(mpolyList(p))

If it's an mpolyList (or has just been converted to one), those are the cases when you can do the print. If you're baking it into a package like m2r, consider this:

vapply(ps, print, character(1), stars = TRUE)  

vapply() is like sapply(), but it's function needs to return a pre-described type (here a character vector of length 1). If you don't want the messages:

suppressMessages( vapply(ps, print, character(1), stars = TRUE) )

In the future, I need to get away from the messages part of print, I don't know why I did that. It really should be print()ed or cat()ed...

dkahle commented 8 years ago

In fact, maybe I should do that now... Ultimately there probably shouldn't be a distinction between an mpoly or mpolyList object, either. Rather, mpoly's should be vectorized like ordinary R objects (e.g. doubles) are.

sommars commented 8 years ago

Thanks, that makes a lot of sense and it will fix the issues I'm having. I guess what still feels a little weird to me is that class(mp(c("x"))) is "mpoly" but class(mp(c("x","y"))) is "mpolyList".

dkahle commented 8 years ago

mp(c("x")) is just the same as mp("x"), since c("x") is the same as "x". Maybe that helps? In any case, give it a little bit and I'll see if I can change the printing mechanism quickly... (Or at least document how to make the changes once I push.)

sommars commented 8 years ago

Ohh, ok. That's completely my ignorance of R showing. I had no idea that a vector of one element is equal to the element in R. That clears everything up.

dkahle commented 8 years ago

Jeff – printing now doesn't message, but it still treats mpoly and mpolyLists differently. That's for another day. In any case, hope that helps!