# Get an instance of a Scala interpreter and see the default settings
s <- scalaInterpreter()
intpSettings(s)
# Demonstrate convenient notation and string interpolation
s %~% 'println("Hello @{Sys.getenv("USER")}")'
intpEval(s,'println("Hello again")') # Results printed to console
intpEval(s,'println("Hello again")',quiet=TRUE) # Console output is suppressed
# Set and get variables
s$rPi <- pi
s$rPi
# Make vectors of length one be set as arrays
intpSettings(s,length.one.as.vector=TRUE)
# Unlike above, now 'pi' is set as an array of length one
s$rPi <- pi
intpGet(s,"rPi")
intpGet(s,"rPi",as.reference=TRUE) # Get the result as a reference
intpSet(s,"rPi",pi,length.one.as.vector=FALSE) # Override current global setting
intpSettings(s,length.one.as.vector=FALSE) # Put it back to the default
# Convenient notation
a1 <- s %~% "rPi/2" # As an R value
a2 <- s %.~% "rPi/2" # As a reference
# References can be set
s$foo <- a2
# Change default to suppress output
intpSettings(s,quiet=TRUE)
s %~% 'println("Hello")'
intpEval(s,'println("Hello")')
intpEval(s,'println("Hello")',quiet=FALSE) # But the default can be overridden
# Get a reference to an R object
myList <- list(a=2, b=matrix(1:8,nrow=2))
wrappedList <- intpWrap(s,myList)
identical(myList,intpUnwrap(s,wrappedList))
s$.myList <- myList
identical(myList,s$myList)
# Instantiate an object
seed <- 2349234L
scalap(s,'scala.util.Random')
rng <- s$do('scala.util.Random')$new(seed) # Scala equivalent: new scala.util.Random(seed)
# Call method of a reference
system.time(rng$nextInt(100L)) # Scala equivalent: rng.nextInt(100)
system.time(rng$nextInt(100L)) # Notice it runs much faster after the first time.
# Call method of companion object and call methods of a reference
# Scala equivalent: (scala.math.BigInt('777',8) - 500).intValue
s$do('scala.math.BigInt')$apply('777',8L)$'-'(500L)$intValue()
# Longer example showing that 'intpDef' is more flexible and faster than '%~%'
intpSet(s,"rng",rng)
drawGaussian <- intpDef(s,'mean: Double, sd: Double','mean+sd*rng.nextDouble')
drawGaussian(3,0.1)
n.draws <- 100
system.time({
draws <- s %~% '
val result = new Array[Double](@{n.draws})
result(0) = rng.nextGaussian
for ( i <- 1 until @{n.draws} ) {
result(i) = 0.5*result(i-1) + rng.nextGaussian
}
result
'
acf(draws,plot=FALSE)
})
sampler <- s$def('nDraws: Int, rho: Double','
val result = new Array[Double](nDraws)
result(0) = rng.nextGaussian
for ( i <- 1 until nDraws ) {
result(i) = rho*result(i-1) + rng.nextGaussian
}
result
')
system.time(acf(sampler(n.draws,0.5),plot=FALSE))
system.time(acf(sampler(n.draws,0.9),plot=FALSE))
Run the code above in your browser using DataLab