Two implicit definitions with same name for a method - scala

I have two implicit declarations that "redefine" x as an operator:
import scala.io.StdIn._
import util._
import scala.language.postfixOps
case class Rectangle(width: Int, height: Int)
case class Circle(ratio: Integer)
case class Cylinder[T](ratio: T, height: T)
object implicitsExample1 {
implicit class RectangleMaker(width: Int) {
def x(height: Int) = Rectangle(width, height)
}
implicit class CircleMaker(ratio: Int) {
def c = Circle(ratio)
}
implicit class CylinderMaker[T](ratio: T) {
def x(height: T) = Cylinder(ratio, height)
}
def main(args: Array[String]) {
val myRectangle = 3 x 4
val myCircle = 3 c
val myCylinder = 4 x 5
println("myRectangle = " + myRectangle)
println("myCircle = " + myCircle)
println("myCylinder = " + myCylinder)
}
}
Here my output gives:
myRectangle = Rectangle(3,4)
myCircle = Circle(3)
myCylinder = Rectangle(4,5)
What I need to do to have something like:
myCylinder = Cylinder[Int](4,5)
I understand that the chosen implicit conversion is the first one declared but is there a way to specify the use of the Cylinder one?

Try combining RectangleMaker and CylinderMaker into a single ShapeMaker implicit class like so
implicit class ShapeMaker[T](width: T) {
def x(height: T)(implicit ev: T =:= Int) = Rectangle(width, height)
def x(height: T) = Cylinder[T](width, height)
}
and provide type ascriptions to value definitions like so
val myRectangle: Rectangle = 3 x 4
val myCircle = 3 c
val myCylinder: Cylinder[Int] = 4 x 5
which outputs
myRectangle = Rectangle(3,4)
myCircle = Circle(3)
myCylinder = Cylinder(4,5)

Related

Creating Singleton Object from a class in Scala

When I was playing with the Scala, I couldn't figure out something. Maybe I am doing completely wrong.
I was trying with Rational Example and Complex Example but I couldn't find a way to use operations like R*3/5 and 1/2*R
here is the complex numbers example I am working on
class Complex(val real : Int, val img : Int){
def this(real: Int) = this(real, 0)
def *(that : Complex) = {
val realPart = this.real * that.real + -(this.img * that.img)
val imgPart = this.real * that.img + this.img * that.real
new Complex(realPart, imgPart)
}
override def toString = this.real + "+" + this.img + "i"
}
object Complex {
def apply(real : Int, img : Int) = new Complex(real, img)
def apply(real : Int) = new Complex(real)
}
object ComplexNumbers {
def main(args: Array[String]) {
import ComplexConversions._
println(Complex(1,2)) // 1+2i
println(I*2) //0+2i
println(2*I) //0+2i
}
}
Well I have tried to create an object I
object I{
def apply() = new Complex(0,1)
def *(that : Complex) = {
val realPart = 0 * that.real + -(1 * that.img)
val imgPart = 0 * that.img + 1 * that.real
new Complex(realPart, imgPart)
}
}
but it did work for the I*2. but I have problems for 2*I. How can I reach the result that I want?
When you call "I * 2", scala looks for a method named "*" on the class of I, and finds it.
When you call "2 * I", scala looks for a method named "*" on the class of 2 (which is Int), and cannot find one.
Even though Int is defined externally, you can add this method to it in Scala via the "implicit conversion" mechanism. This is covered briefly in the "implicits" example and in more detail elsewhere, e.g. here
Try adding some code like the following to your "Complex" object:
object Complex {
implicit class IntOps(x: Int) {
def *(y: Complex) = y * x
}
}
You'll also need to declare I as a val, rather than an Object for this to work:
val I = Complex(0, 1)
(or add an implicit method like class Complex { def *(i: I) = ... }, but that's much uglier)
(I assume by Complex Example, you mean this?)
Working code:
class Complex(val real : Int, val img : Int){
def this(real: Int) = this(real, 0)
def *(that : Complex) = {
val realPart = this.real * that.real + -(this.img * that.img)
val imgPart = this.real * that.img + this.img * that.real
new Complex(realPart, imgPart)
}
override def toString = this.real + "+" + this.img + "i"
}
object Complex {
def apply(real : Int, img : Int) = new Complex(real, img)
def apply(real : Int) = new Complex(real)
val I = Complex(0, 1)
implicit def toComplex(x: Int): Complex = new Complex(x)
}
object ComplexNumbers {
def main(args: Array[String]) {
import Complex._
println(Complex(1,2)) // 1+2i
println(I*2) //0+2i
println(2*I) //0+2i
}
}
If you want to be able to use 2*I, you will need to add a new * override for the Int class (since * is really a method of the class Int, meaning 2*I is really 2.*(I)).
You can accomplish this with an implicit class:
scala> case class myInt(i: Int){
| def mult(that: Int): myInt = myInt(that * i)
| }
defined class myInt
scala> implicit class intOverride(i: Int){
| def *(that: myInt): myInt = that.mult(i)
| }
defined class intOverride
scala> val a = myInt(2)
a: myInt = myInt(2)
scala> 2 * a
res1: myInt = myInt(4)

Using a double value in a Fractional[T] method

I have the following function which generates a Uniform distributed value between 2 bounds:
def Uniform(x: Bounded[Double], n: Int): Bounded[Double] = {
val y: Double = (x.upper - x.lower) * scala.util.Random.nextDouble() + x.lower
Bounded(y, x.bounds)
}
and Bounded is defined as follows:
trait Bounded[T] {
val underlying: T
val bounds: (T, T)
def lower: T = bounds._1
def upper: T = bounds._2
override def toString = underlying.toString + " <- [" + lower.toString + "," + upper.toString + "]"
}
object Bounded {
def apply[T : Numeric](x: T, _bounds: (T, T)): Bounded[T] = new Bounded[T] {
override val underlying: T = x
override val bounds: (T, T) = _bounds
}
}
However, I want Uniform to work on all Fractional[T] values so I wanted to add a context bound:
def Uniform[T : Fractional](x: Bounded[T], n: Int): Bounded[T] = {
import Numeric.Implicits._
val y: T = (x.upper - x.lower) * scala.util.Random.nextDouble().asInstanceOf[T] + x.lower
Bounded(y, x.bounds)
}
This works swell when doing a Uniform[Double](x: Bounded[Double]), but the other ones are impossible and get a ClassCastException at runtime because they can not be casted. Is there a way to solve this?
I'd suggest defining a new type class that characterizes types that you can get random instances of:
import scala.util.Random
trait GetRandom[A] {
def next(): A
}
object GetRandom {
def instance[A](a: => A): GetRandom[A] = new GetRandom[A] {
def next(): A = a
}
implicit val doubleRandom: GetRandom[Double] = instance(Random.nextDouble())
implicit val floatRandom: GetRandom[Float] = instance(Random.nextFloat())
// Define any other instances here
}
Now you can write Uniform like this:
def Uniform[T: Fractional: GetRandom](x: Bounded[T], n: Int): Bounded[T] = {
import Numeric.Implicits._
val y: T = (x.upper - x.lower) * implicitly[GetRandom[T]].next() + x.lower
Bounded(y, x.bounds)
}
And use it like this:
scala> Uniform[Double](Bounded(2, (0, 4)), 1)
res15: Bounded[Double] = 1.5325899033654382 <- [0.0,4.0]
scala> Uniform[Float](Bounded(2, (0, 4)), 1)
res16: Bounded[Float] = 0.06786823 <- [0.0,4.0]
There are libraries like rng that provide a similar type class for you, but they tend to be focused on purely functional ways to work with random numbers, so if you want something simpler you're probably best off writing your own.

A method that should only accept instances of A or B or C in Scala

I would ensure that a method should only accept instances of A or B or C. And I don't want to modify the code of A, B and C.
case class A
case class B
case class C
def method(aOrbOrc: Any) = ???
// method("toto") should not compile
You can use Type Class.
case class A(s: String)
case class B(i: Int)
case class C(i1: Int, i2: Int)
// Type Class
trait ABC[T] {
def bar(t: T): String
}
// Instances
implicit object ABC_A extends ABC[A] {
override def bar(t: A): String = "A : s = " + t.s
}
implicit object ABC_B extends ABC[B] {
override def bar(t: B): String = "B : i = " + t.i
}
implicit object ABC_C extends ABC[C] {
override def bar(t: C): String = "C : i1 = " + t.i1 + ", i2 = " + t.i2
}
def method[T](abc: T)(implicit instance: ABC[T]) = println(instance.bar(abc))
method(A("AAAAA")) // => A : s = AAAAA
method(B(123)) // => B : i = 123
method(C(9, 5)) // => C : i1 = 9, i2 = 5
method(1) // compilation error
You could use Miles Sabin's idea for implementing union types (code below is taken from Rex Kerr's variant):
trait Contra[-A] {}
type Union[A,B,C] = {
type Check[Z] = Contra[Contra[Z]] <:< Contra[Contra[A] with Contra[B] with Contra[C]]
}
then do:
def method[T: Union[A,B,C]#Check](t: T) = ???
for example:
def method[T: Union[Int,String,Boolean]#Check](t:T) = ???
method(1) // OK
method("foo") // OK
method(true) // OK
method(1.5) // does not compile
Read more about it here. And here is a link to Miles' post.

Generic value-classes in Scala

Let's say I have a type Pos (for position). In order to gain type-safety the column/row is not represented as Int but by types Col (column) and a Row:
case class Pos(col: Col, row: Row) {
def +(other: Pos): Pos = Pos(col + other.col, row + other.row)
}
It's possible to add two positions, which consists of summing columns and rows respectively.
The definition of types Col and Row would look like this:
object Row {
def apply(value: Int) = new Row(value)
val zero = new Row(0)
}
object Col {
def apply(value: Int) = new Col(value)
val zero = new Col(0)
}
class Row(val value: Int) extends AnyVal {
def +(other: Row): Row = Row(this.value + other.value)
}
class Col(val value: Int) extends AnyVal {
def +(other: Col): Col = Col(this.value + other.value)
}
This is all fine, but I have the feeling of repeating myself. The definitions are almost identical.
Could I do something to generalize them?
If you introduce Scalaz and create Monoid instances for Row and Col, you may not reduce your boilerplate, but it would shorten your definition of zero and append some:
case class Col(i: Int) extends AnyVal
case class Row(i: Int) extends AnyVal
implicit object rowMonoid extends Monoid[Row] {
def zero = Row(0)
def append(a: Row, b: => Row) = Row(a.i |+| b.i)
}
implicit object colMonoid extends Monoid[Col] {
def zero = Col(0)
def append(a: Col, b: => Col) = Col(a.i |+| b.i)
}
And Monoids are composable, so if you stored Rows and Cols in a map, or tuple or the like, you could just compose them, without hitting the individual elements:
val pt1 = (Row(4), Col(15))
val pt2 = (Row(14), Col(5))
val res = pt1 |+| pt2
println(res) // (Row(18),Col(20))
I think simplifying the usage will save you more code overall than worrying about trimming down the definitions, assuming Row and Col are used and added often.
You can define a common trait for Both Row and Col classes:
trait Element {
val value : Int
def init(value: Int): Element
def +(other: Element) = init(value + other.value)
}
and then use case classes so that you take advantage of the companion object's apply method:
case class Row(value: Int) extends Element {
def init(v: Int) = Row(v)
}
case class Col(value: Int) extends Element {
def init(v: Int) = Col(v)
}
So now you can add them like that:
case class Pos(col: Element, row: Element) {
def +(other: Pos): Pos = Pos(col + other.col, row + other.row)
}
val p1 = Pos(Col(1), Row(2))
val p2 = Pos(Col(1), Row(2))
p1 + p2 //res2: Pos = Pos(Col(2),Row(4))
However, this allows to create a position with only rows
val p3 = Pos(Row(2), Row(3))
p1 + p3 //res3: Pos = Pos(Col(3),Row(5))
So a second step is to bound your Element type's + method.
trait Element[T <: Element[_]] {
val value : Int
def init(value: Int): Element[T]
def +(other: Element[T]) = init(value + other.value)
}
case class Row(value: Int) extends Element[Row] {
def init(v: Int) = Row(v)
}
case class Col(value: Int) extends Element[Col] {
def init(v: Int) = Col(v)
}
case class Pos(col: Element[Col], row: Element[Row]) {
def +(other: Pos): Pos = Pos(col + other.col, row + other.row)
}
What you get is that now a row should only add elements of a row type and a Col should only add elements of a Col type. You can still add two positions:
val p1 = Pos(Col(1), Row(2))
val p2 = Pos(Col(1), Row(2))
p1 + p2 //res0: Pos = Pos(Col(2),Row(4))
but this will not compile:
val p3 = Pos(Row(2), Row(3))
You can use type variable in your trait
Something like this
trait TableElement{
type T
def +(t:T):T
}

scala's spire framework : I am unable to operate on a group

I try to use spire, a math framework, but I have an error message:
import spire.algebra._
import spire.implicits._
trait AbGroup[A] extends Group[A]
final class Rationnel_Quadratique(val n1: Int = 2)(val coef: (Int, Int)) {
override def toString = {
coef match {
case (c, i) =>
s"$c + $i√$n"
}
}
def a() = coef._1
def b() = coef._2
def n() = n1
}
object Rationnel_Quadratique {
def apply(coef: (Int, Int),n: Int = 2)= {
new Rationnel_Quadratique(n)(coef)
}
}
object AbGroup {
implicit object RQAbGroup extends AbGroup[Rationnel_Quadratique] {
def +(a: Rationnel_Quadratique, b: Rationnel_Quadratique): Rationnel_Quadratique = Rationnel_Quadratique(coef=(a.a() + b.a(), a.b() + b.b()))
def inverse(a: Rationnel_Quadratique): Rationnel_Quadratique = Rationnel_Quadratique((-a.a(), -a.b()))
def id: Rationnel_Quadratique = Rationnel_Quadratique((0, 0))
}
}
object euler66_2 extends App {
val c = Rationnel_Quadratique((1, 2))
val d = Rationnel_Quadratique((3, 4))
val e = c + d
println(e)
}
the program is expected to add 1+2√2 and 3+4√2, but instead I have this error:
could not find implicit value for evidence parameter of type spire.algebra.AdditiveSemigroup[Rationnel_Quadratique]
val e = c + d
^
I think there is something essential I have missed (usage of implicits?)
It looks like you are not using Spire correctly.
Spire already has an AbGroup type, so you should be using that instead of redefining your own. Here's an example using a simple type I created called X.
import spire.implicits._
import spire.algebra._
case class X(n: BigInt)
object X {
implicit object XAbGroup extends AbGroup[X] {
def id: X = X(BigInt(0))
def op(lhs: X, rhs: X): X = X(lhs.n + rhs.n)
def inverse(lhs: X): X = X(-lhs.n)
}
}
def test(a: X, b: X): X = a |+| b
Note that with groups (as well as semigroups and monoids) you'd use |+| rather than +. To get plus, you'll want to define something with an AdditiveSemigroup (e.g. Semiring, or Ring, or Field or something).
You'll also use .inverse and |-| instead of unary and binary - if that makes sense.
Looking at your code, I am also not sure your actual number type is right. What will happen if I want to add two numbers with different values for n?
Anyway, hope this clears things up for you a bit.
EDIT: Since it seems like you're also getting hung up on Scala syntax, let me try to sketch a few designs that might work. First, there's always a more general solution:
import spire.implicits._
import spire.algebra._
import spire.math._
case class RQ(m: Map[Natural, SafeLong]) {
override def toString: String = m.map {
case (k, v) => if (k == 1) s"$v" else s"$v√$k" }.mkString(" + ")
}
object RQ {
implicit def abgroup[R <: Radical](implicit r: R): AbGroup[RQ] =
new AbGroup[RQ] {
def id: RQ = RQ(Map.empty)
def op(lhs: RQ, rhs: RQ): RQ = RQ(lhs.m + rhs.m)
def inverse(lhs: RQ): RQ = RQ(-lhs.m)
}
}
object Test {
def main(args: Array[String]) {
implicit val radical = _2
val x = RQ(Map(Natural(1) -> 1, Natural(2) -> 2))
val y = RQ(Map(Natural(1) -> 3, Natural(2) -> 4))
println(x)
println(y)
println(x |+| y)
}
}
This allows you to add different roots together without problem, at the cost of some indirection. You could also stick more closely to your design with something like this:
import spire.implicits._
import spire.algebra._
abstract class Radical(val n: Int) { override def toString: String = n.toString }
case object _2 extends Radical(2)
case object _3 extends Radical(3)
case class RQ[R <: Radical](a: Int, b: Int)(implicit r: R) {
override def toString: String = s"$a + $b√$r"
}
object RQ {
implicit def abgroup[R <: Radical](implicit r: R): AbGroup[RQ[R]] =
new AbGroup[RQ[R]] {
def id: RQ[R] = RQ[R](0, 0)
def op(lhs: RQ[R], rhs: RQ[R]): RQ[R] = RQ[R](lhs.a + rhs.a, lhs.b + rhs.b)
def inverse(lhs: RQ[R]): RQ[R] = RQ[R](-lhs.a, -lhs.b)
}
}
object Test {
def main(args: Array[String]) {
implicit val radical = _2
val x = RQ[_2.type](1, 2)
val y = RQ[_2.type](3, 4)
println(x)
println(y)
println(x |+| y)
}
}
This approach creates a fake type to represent whatever radical you are using (e.g. √2) and parameterizes QR on that type. This way you can be sure that no one will try to do additions that are invalid.
Hopefully one of these approaches will work for you.