Home Comments Thread
New Thread

You Should Rarely Need `eval(parse())` | /en/2023/02/eval-parse/

giscus giscus 2023-09-07 14:04:45

You Should Rarely Need eval(parse())

Many programming languages have a function to evaluate a string as code or an expression, e.g., eval() in R. Once you learn it, it becomes tempting to abuse it. Instead of writing code naturally and …

https://yihui.org/en/2023/02/eval-parse/

1 Comment

fncokg fncokg 2023-09-07 14:04:46

I found that in function ppclust::fcm, there are many codes like this:

compd <- parse(text = paste0(".compdist(x[i,], v[j,], dmetric='", dmetric, "', p=", pw, ")"))
# some other codes
for(j in 1:k)
    for(i in 1:n)
        d[i,j] <- eval(compd)

I'm surprised and I wonder why not simply replace those codes with this:

for(j in 1:k)
    for(i in 1:n)
        d[i,j] <- .compdist(x[i,],v[j,],dmetric=dmetric,p=pw)
yihui yihui 2023-09-07 14:16:47

Indeed there are many eval() calls in this package: https://github.com/search?q=repo%3Acran%2Fppclust+eval%28&type=code I think you are right that these eval(parse()) calls are unnecessary. You may contact its authors and see if we missed anything.

Sign in to join the discussion

Sign in with GitHub