Scala Worksheet issues with values and output - eclipse

Finding quite a big error on the Scala worksheet whilst in Eclipse 3.7.2 downloaded fromTypesafe for a Linux, Ubuntu
Seem to get issues when defining values - something which doesn't happen on my course teachers screen.
Please see as follows:
package week3
object rational2 {
val x = new Rational(1,2) //> x : week3.Rational = week3.Rational#1e9cb75
x.num //> res0: Int = 1
x.den //> res1: Int = 2
val y = new Rational(2,3) //> y : week3.Rational = week3.Rational#1786e64
x.addRationals(y) //> res2: week3.Rational = week3.Rational#197a37c
val z = new Rational(3,2) //> z : week3.Rational = week3.Rational#6e3d60
As you can see it doesn't even tell me what x, y, z are but points to a variable defined as the being within the package.
Previously had a known issue of highlighting errors when there wasn't one, but had to reinstall Eclipse to get rid of these.
Any help appreciated.
EDIT: please note a Rational class has been defined, beneath the object one - I simply didn't paste it as it doesn't show any errors and isn't dealt with by the interactive worksheet

What you're seeing is the toString representation of the Rational class. You haven't defined one so it just goes with the default.
You're probably meant to define Rational as a case class, which will give you a sensible toString representation automatically.

Related

Finding area under the curve(Integration) in Scala from Array of values

Hi does anyone know of a standard library that can do what is specified in the title. Ideally the usage should be something like this: https://docs.scipy.org/doc/numpy/reference/generated/numpy.trapz.html
I researched quite a lot and couldn't finding anything similar.
Everything used apache PolynomialFunction class which takes as inputs the polynomial parameters and not the y-coordinates
Using Breeze you can write any type of function that type checks and pass it to trapezoid, you can just include the mapping in the function:
val f = (x: Double) => {
val xToY = Map(1.0 -> 1.0 , 2.0 -> 2.0, 3.0 -> 3.0)
xToY(x)
}
scala> import breeze.integrate._
scala> trapezoid(f, 1, 3, 3)
res0: Double = 4.0
Although it has restricted use, as it needs the mapping not to have gaps between the range it defined.

Ways of aliasing in scala?

I am trying to figure out if Scala programming language has a way of Aliasing(presence of two or more distinct referencing methods for the same memory location).
I can see example of type aliasing such as "x: (Int, String) = (1,one)". So x has two different types but do they share same memory?
I would greatly appreciate if anyone could give more explanation.
If you want one "variable" to track another, you could do something like this.
scala> var x = 5 // create a variable
x: Int = 5
scala> def y = x // keep track of x
y: Int
scala> x = 9 // change x
x: Int = 9
scala> y // yep, y changes too
res1: Int = 9
This isn't a true alias. You can't modify y and see the change in x. A def is simply re-evaluated every time it is invoked, so every time you query y, it re-examines x for the current value.
Note that this type of thing is not considered good Scala practice. In Functional Programming you want to avoid data structures that maintain state, i.e. don't use a var if you don't have to, and good Scala programmers almost never have to.

Get objects out of scala interpreter

I spent hours investigating one topic. I am definitely out of my depth here. What I want is to run the scala interpreter programmatically and be able to extract object values from the interpreter. for example, if I send
val a = 1
val b = a + 1
I want to be able to read out b as an Int, not just a string printed out like
b = 2
The source code is dense. So far I don't see any part which would allow such an extraction. Any experts here who can give me a tip or tell me this is utter nonsense?
How do I get typed objects out of the scala interpreter between sessions?
Use JSR 223.
Welcome to Scala version 2.11.7 [...]
scala> import javax.script._
import javax.script._
scala> val engine = (new ScriptEngineManager).getEngineByName("scala")
engine: javax.script.ScriptEngine = scala.tools.nsc.interpreter.IMain#4233e892
scala> engine.eval("val a = 1")
res0: Object = 1
scala> engine.eval("val b = a + 1")
res1: Object = 2
scala> engine.eval("b").asInstanceOf[Int]
res2: Int = 2

Scala convert Option to an Int

I have looked at these links
http://blog.danielwellman.com/2008/03/using-scalas-op.html
http://blog.tmorris.net/scalaoption-cheat-sheet/
I have a map of [String, Integer] and when I do a map.get("X") I get an option. I would like the following.
val Int count = map.get(key);
// If the key is there I would like value if it is not I want 0
How do I achieve this in one line? I need to do this several times. It looks a bit inefficient to write a function everytime for doing this. I am sure there is some intelligent one line quirk that I am missing but I really like to get the value into an integer in ONE line :)
Just use getOrElse method:
val count: Int = map.getOrElse(key,0);
Note also, that in Scala you write type after name, not before.
#om-nom-nom (classic screen name) has the correct answer, but in the interest of providing yet another way™
val count = map.get(key) fold(0)(num => num)
Before in-the-know users bash me with, "Option has no fold!", fold has been added to Option in Scala 2.10
getOrElse is of course better in the current case, but in some Some/None scenarios it may be interesting to 1-liner with fold like so (edited complements of #Debiliski who tested against latest 2.10 snapshot):
val count = map.get(k).fold(0)(dao.userlog.count(_))
I suppose in 2.9.2 and under we can already do:
val count = map get(k) map ( dao.userlog.count(_) ) getOrElse(0)
Which is to say, in Scala there is often more than one way to do the same thing: in the linked thread, the OP shows more than 10 alternative means to achieve Option fold ;-)
Yet another way.
import scalaz._, Scalaz._
scala> val m = Map(9 -> 33)
m: scala.collection.immutable.Map[Int,Int] = Map(9 -> 33)
scala> m.get(9).orZero
res3: Int = 33
scala> m.get(8).orZero
res4: Int = 0

Equal Sign and Type Mismatch

When working with the standard widget toolkit (SWT), I usually use something like this to define my GridLayout:
layout.marginTop = layout.marginBottom =
layout.marginLeft = layout.marginRight =
layout.horizontalSpacing = layout.verticalSpacing = 20
It works in java but not in scala.
It gives me type mismatch; Found: Unit Required: Int.
So how can this solve it?
You cannot do this in one line in scala because the result type of an assignment expression (e.g. a = b) is Unit. You'd have to have 6 separate calls:
layout.marginTop = 20
layout.marginBottom = 20
... etc
Why is the result type of an assignment Unit and nmot the assigned value? I believe this was chosen for performance reasons as outlined in this question.
There is a related question on assignment which points out that at declaration site, it is possible via:
val a, b, c = X
You have to write multiple assignments separately. As the compiler says, an assignment in Scala returns Unit, which can be seen as Java's void.
You could do
def assign[A](a:A)(fs: (A => Unit)*) = fs.foreach(_(a))
val r = new java.awt.Rectangle
assign(20)(r.x=_, r.y=_, r.width=_, r.height=_)
But this is clearly worse than writing everything separately. But at least you don't have to type "layout" every time in Scala:
val rectangle = new java.awt.Rectangle
import rectangle._
x = 20
y = 20
width = 20
height = 20