Type Class for Complex Numbers - complex-numbers

I need to implement a custom type class for Complex DSP and Complex Ring operations. I'm aware about DspTools project, but purposely want to exclude it from consideration.
I've got a hardware module, which I want to instantiate with diff type classes: UInt, SInt, FixedPoint, Real and Complex(FixedPoint, FixedPoint).
Here's my minimal class:
class Complex[A <: Data, B <: Data] (val re:A, val im:B) extends Bundle {
override def cloneType: this.type = new Complex(re, im).asInstanceOf[this.type]
}
object Complex {
def apply[A <: Data, B <: Data](re:A, im:B) = new Complex(re, im)
implicit def UInt2Complex(re:UInt, im:UInt) = Complex(re,im)
}
When I instantiate this with different data types from Chisel3.Core, the code compiles and works.
However, when I try to do :
import chisel3.core.{FixedPoint => FP}
...
val inType = Complex ( FP(20.W,10.BP), FP(20.W,10.BP))
val outType = Complex ( FP(20.W,10.BP), FP(20.W,10.BP))
...
I get the code compiled, but FIRRTL emits an error:
[info] using --backend-name verilator
[info] chisel3.core.Binding$RebindingException: Attempted reassignment of binding to chisel3.core.FixedPoint#d
[info] at chisel3.core.Data.binding_$eq(Data.scala:250)
What's wrong with this? How to fix the issue?

The issue is that Chisel needs fresh clones of any Data when it recursively calls cloneType, and you're simply passing re and im to the Complex constructor resulting in the exact same objects. Put a little more concretely:
val a = Complex(UInt(8.W), UInt(8.W))
val b = a.cloneType
a.re eq b.re // This will be true and it *must* not be
This is kind of an age old problem that we don't have a great solution to, in your case, you should call .cloneType on re and im in Complex.cloneType
I know you aren't using DSPTools, but it can still provide a reference and they do that: https://github.com/ucb-bar/dsptools/blob/fe8f9d08987f3a403f6281ba4face1c26b627b71/src/main/scala/dsptools/numbers/chisel_concrete/DspComplex.scala#L75

Here's the actual minimalistic implementation, which worked for me. #jkoenig pointed me to the right direction. Thanks a lot!
class Complex[A <: Data, B <: Data] (val re:A, val im:B) extends Bundle {
override def cloneType: this.type = new Complex(re.cloneType, im.cloneType).asInstanceOf[this.type]
}
object Complex {
def apply[A <: Data, B <: Data](re:A, im:B):Complex[A,B] = {
val real = re.cloneType
val imag = im.cloneType
new Complex(real,imag)
}
}

Related

More elegant way to call getter within deeply nested data classes

I have deserialized a huge XML file and that leaves me with a lot of (nested) data classes. I'm looking for a more elegant way to do calls to specific getters within these objects. So I would rather not fill my code with all these dot calls.
I have to set quite some fields to return a new Model, which currently looks something like this (I made up the model for this question):
return TestClass(
appointmentDate = message.data.appointment.appointmentDescription.AppointmentDetails.appointmentDate
appointmentX = message.data.appointment.appointmentDescription.X.Y.Z
appointmentY = message.data.appointment.appointmentDescription.AppointmentDetails.X.Y.Z
appointmentZ = message.data.appointment.Z
)
I know I could do val appointmentDescription = message.data.appointment.appointmentDescription and do my calls from there to shorten it a bit, but there must be a shorter and better way I assume.
Does anyone know a way to do this in a more elegant and clean way? I'm pretty new to Kotlin and it is quite hard for me to properly lookup any solutions on the internet since I can't find any and am probably searching for the wrong things.
Try the with function:
data class Message (val data: Data)
data class Data (val appointment: Appointment)
data class Appointment(val appointmentDescription: AppointmentDescription)
data class AppointmentDescription(val x: Int, val appointmentDetails: AppointmentDetails)
data class AppointmentDetails(val x:Int, val y:Int)
fun TestClass(message: Message) {
with(message.data.appointment.appointmentDescription) {
val appointmentX = x
val appointmentY = appointmentDetails.y
}
}
This should be useful: https://medium.com/mobile-app-development-publication/mastering-kotlin-standard-functions-run-with-let-also-and-apply-9cd334b0ef84

Class method signature based on supplied type in Kotlin?

I'm trying to reduce boilerplate on something I'm working on and wondering if something is possible - I suspect it's not but was looking for confirmation
class Something<T> {
private val list = mutableListOf<T>()
fun addToList(value: T) = list.add(value) }
So if I wanted to use this with a class like:
class Data(number: Int, letter: Char)
I'd have to use addToList like:
addToList(Data(1,"a"))
Is there some way to use the supplied type T to construct the method addToList dynamically? So that the class would be instantiated like:
val thing = Something<Data>()
but then addToList were called like
addToList(1,"a")
Like I said, don't think this is possible but was looking for confirmation.
What I was really trying to do was come up with something that would allow me to do this without declaring Data at all, but instead just define the structure and the subsequent addToList method when Something() was instantiated - not sure if I have described this all that well but if anyone has any suggestions in general around that I'd be grateful!
Thanks!
There are Pair and Triple tuple classes provided in the standard library which allows you to avoid declaring a class for simple combinations of values. If you need more than 3 parameters of different types, you'd need to create your own class or use a library that provides larger tuple classes. If all types are the same, you can use List instead of a tuple.
In my opinion even Triple is pushing it and anything with more than two distinct properties should just have its own data class defined.
class Something<A, B> {
private val list = mutableListOf<Pair<A, B>>()
fun addToList(valueA: A, valueB: B) = list.add(Pair(valueA, valueB))
}
val something = Something<Int, String>()
something.addToList(1, "a")
An alternate approach if you want to keep the flexibility of your Something class to hold anything would be to use an extension function.
class Something<T> {
private val list = mutableListOf<T>()
fun addToList(value: T) = list.add(value)
}
fun <A, B> Something<Pair<A, B>>.addToList(valueA: A, valueB: B) =
addToList(Pair(valueA, valueB))
val something = Something<Pair<Int, String>>()
something.addToList(1, "a")

In Kotlin, how do I create an instance of a class where the class name is a variable?

I am writing a Graph class in Kotlin. Here's my code so far:
import java.util.*
class Graph<Class>(connectionProb: Double) {
// a general network class
val nodes = mutableListOf<Class>()
val connectionProb = connectionProb
val connections = hashMapOf<Class, MutableList<Class>>()
var nextID = 0
private fun createNode() {
// Here is where I need help
}
}
I want to be able to specify the node type for each Graph. The code above will compile, but I'm unsure how to initialize new nodes. The only argument I want to pass into each node, regardless of its type, is nextID.
Thanks!
First thing you should do is define a class for your graph node, and instead of maintaining a map for connections, let every node maintain a list of its connections.
So your code would look like this
class Graph<T>(connectionProb: Double) {
var nextId = 0
val nodes = mutableListOf<Node<T>>()
// Define a node class, so if you have graph of Integer then you want a node of Integer
class Node<T>(var id: Int){
val connections = mutableListOf<Node<T>>()
fun addConnection(newConnection: Node<T>){
connections.add(newConnection)
}
override fun toString() = "$id"
/** add other functions, such as remove etc */
}
fun createNode(){
var newNode = Node<T>(nextId++)
nodes.add(newNode)
}
}
Now to use this graph you will do followig
fun main(){
var myGraph = Graph<Integer>(10.9)
myGraph.createNode()
myGraph.createNode()
myGraph.nodes[0].addConnection(myGraph.nodes[1])
/* Print all nodes in graph */
for(node in myGraph.nodes) print(" $node")
/* Print connections of first node */
for(node in myGraph.nodes[0].connections) print("\n\nConnection id: $node")
}
Please note that this will give you a general idea of how to go about implementing graph and there are many things that you can improve in the implementation. To learn more I suggest you read a good book, such as Data Structures and Algorithms in Java

Can I update a deeply nested immutable object without making it aware of its context?

Let's imagine I have a nested immutable object graph, along these lines (using Kotlin syntax, but hopefully it's clear):
data class House(val bedroom: Bedroom, val bathroom: Bathroom, val kitchen: Kitchen)
class Bedroom
class Bathroom
data class Kitchen(val oven: Oven, val kettle: Kettle)
class Oven
data class Kettle(val on: Boolean)
var house = House(Bedroom(), Bathroom(), Kitchen(Oven(), Kettle(false)))
Now, I want to switch the kettle on. If the objects were mutable I would just write:
data class Kettle(var on: Boolean) {
fun activate() {
this.on = true
}
}
house.kitchen.kettle.activate()
But because they are immutable I have to write:
data class Kettle(val on: Boolean) {
fun activate(house: House): House {
return house.copy(kitchen = kitchen.copy(kettle = kettle.copy(on = true)))
}
}
house = house.kitchen.kettle.activate(house)
(Actually, it's slightly more complicated, but this pseudo-code will do).
I don't like this, not because it's long, per se, but because the Kettle now needs to know not just about its own internal state, but about the full context it exists in.
How can I rewrite this so that each object can be responsible for providing its own mutation logic, without having to be aware of the full object graph? Or am I just trying to marry object-oriented and functional concepts in an impossible way?
This is where functional lenses show their power. For example, using poetix/klenses,
val kettleLens = +House::kitchen + Kitchen::kettle
var house = House(...)
house = kettleLens(house) { copy(on = true) }
One possible approach I thought of (this is the question asker, by the way) was like this:
data class Kettle(val on: Boolean) {
fun activate() {
return Transform(this, Kettle(on = true))
}
}
class Transform<T>(val what: T, val replacement: T) {
fun <U> apply(x: U): U {
if (x is T && x == what) {
return replacement as U
} else {
return x
}
}
}
The idea here is that a transform is a function you can apply to every object in the graph and it will only modify the what you told it to modify.
So you use it like this:
val transform = house.kitchen.kettle.activate()
house = house.transformEverything(transform)
Where every class has an implementation like this:
data class House(val bedroom: Bedroom, val bathroom: Bathroom, val kitchen: Kitchen) {
fun transformEverything(transform: Transform): House {
return transform(this).copy(
bedroom = bedroom.transformEverything(transform),
bathroom = bathroom.transformEverything(transform),
kitchen = kitchen.transformEverything(transform)
)
}
}
Which recursively gives the transform a chance to modify every object it wants to, and it will only apply it to one.
This approach is bad because:
Tons of boiler-plate giving everything its own dumb version of the transformEverything method
It seems weird (and inefficient) to have to call an function on every object in the graph just to change one.
But it does achieve my goal of the Kettle not needing to know anything about its context, and it's pretty straightforward to write the activate function. Thoughts?

Approaches to testing that a method is not available on a type

Given a type hierarchy for a game which strongly distinguishes whose turn is next:
trait Game
trait BlackToPlay extends Game {
def move(p: BlackPiece, s: Square): Either[FinishedGame, WhiteToPlay]
}
trait WhiteToPlay extends Game {
def move(p: WhitePiece, s: Square): Either[FinishedGame, BlackToPlay]
}
Can I make the following, important assertion without resorting to reflection?
"A game with white to play" should {
"not allow black to play" in {
// an instance of whiteToPlay should not
// have the `move(BlackPiece, Square)` method.
}
}
EDIT: My attempt to implement #Martin's solution doesn't work. Any thoughts on what's wrong here? From the REPL:
scala> class B() {
| def b(s: String) = s
| }
defined class B
scala> val b = new B()
b: B = B#420e44
scala> b.c("")
<console>:8: error: value c is not a member of B
b.c("")
^
scala> b match {
| case _: { def c(s: String) } => false
| case _ => true
| }
warning: there were unchecked warnings; re-run with -unchecked for details
res7: Boolean = false
res7 should have been true, because b should not match on the structural type of { def c(s: String) }
You don't test what the type system already guarantees. In fact, the type system is already a test of certain properties of your program.
You could further on to test that the types you have guarantee a certain property (like no player making a move twice in a row), but this kind of thing is restricted to languages like Agda and Coq, for now.
Assuming BlackPiece is not a subtype of WhitePiece:
WhiteToPlayInstance.move(BlackPiece, s) should not compile - which means you can't write a test for it. The type system ensures that you can't move a BlackPiece on a WhiteToPlay.
EDIT: As Thomas pointed out, the below answer is nonsense since structural types cannot be used in pattern matches in the JVM version of scala.
Under normal cicumstances this doesnt make much sense because scala is statically typed and things like that are taken care of by the compiler but if you do make massive use of reflection or structural typing in your code it might be a good test:
instance match {
case x: { def move(p: BlackPiece, s: Square): Either[FinishedGame, WhiteToPlay] } => // error
case _ => // no error
}
If you really want to test for such things, move the check from type checking to something dynamic. Assume that WhitePiece and BlackPiece share a common supertype Piece:
trait Game {
def move(p : Piece, s : Square) : Either[FinishedGame, WhiteToPlay]
}
trait BlackToPlay extends Game
trait WhiteToPlay extends Game
Then a test could look like this:
val b2p : BlackToPlay = ...
val bp : BlackPiece = ...
val wp : WhitePiece = ...
{a move bp} must not produce [IllegalMoveException]
{a move wp} must produce [IllegalMoveException]
I am not sure this would be good design, but it makes your system explicitly testable.
I know you didn't want a reflection solution, but you could (if scala 2.9 is acceptable) use the new Dynamic trait like this:
class ReflectionDynamic[T <: AnyRef](t: T) extends Dynamic {
def typed[A]: A = sys.error("doh");
def applyDynamic(name: String)(args: Any*) = {
val argRefs = args.map {
case a: AnyRef => a
case _ => sys.error("only AnyRefs")
}
t.getClass.getMethod(name, argRefs.map(_.getClass): _*).invoke(t, argRefs: _*)
}
}
... and that will give this positive test:
val dynamicWhiteToPlay = new ReflectionDynamic(whiteToPlay)
dynamicWhiteToPlay.move(new WhitePiece, new Square) must_== Right(blackToPlay)
... and this for negative:
dynamicWhiteToPlay.move(new BlackPiece, new Square) must throwA[NoSuchMethodException]
The question is akin to asking: Given val f: (Boolean) => Int, how can I test that f("hello world") is rejected by the compiler?
After some brief conversation at the Melbourne Scala User Group my question was validated (yay). After all, the restriction I'm trying to test for is included by design and therefore deserves a test.
Bernie Pope suggested that the mechanism required is Automated Theorem Proving. #daniel-c-sobral was kind enough to mention Agda and Coq in a slightly different context and indeed these are ATP technologies which could prove my application to be correct.
Another suggestion was to execute the offending code as a script and assert that it fails. A poor-mans eval, if you like.