Combining Sets in xtend - xtend

I have two sets:
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = #{3, 4, 5} + setA
I would expect setB to contain 1, 2, 3, 4, 5.
However, the + operator returns an instance of Iterable, instead of a Set.
Are there any xtend shortcuts that would allow me to do what I want?

I'm afraid there is no backed in support for a union. You may want to add an operator_plus for two sets and delegate to Guavas Sets.union.
def <T> Set<? extends T> operator_plus(Set<? extends T> left, Set<? extends T> right) {
return Sets.union(left, right)
}

Without redefining operators, you have to convert the Iterable to a Set manually.
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = (#{3, 4, 5} + setA).toSet
If you have a mutable set, there is one other way: The += operator, which is a shortcut for addAll on any collection.
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = newHashSet(3, 4, 5)
setB += setA
Neither solution look particularly nice and you probably want to avoid mutability.
As suggested in the other answer, Guava's Sets.union method might come in handy, though I would rather import it as static extension than redefining operators. Then you can use:
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = #{3, 4, 5}.union(setA)
Be careful though, union returns a view of both sets, which can change if the underlying sets are mutable.

Related

Poking individual bits using peekpoketester

I have an IO bundle as shown below
val io = IO(new Bundle{
val test = Input(UInt(32.W))
})
Now from the testbench I want to give inputs to the test pin. I know that we can use peekpoketesters to give an input like this
poke(dut.io.test, 40.U)
But is there a way I can use peekpoketester to set the individual bits of the test input pin?
For example something like this
poke(dut.io.test(31,23) , 6.U)
The short answer is no, poking to specific bits of an input is not directly supported, but using the fact that you can peek top level inputs here is a very simplistic workaround. You can run and test this on scastie here.
You could generalize this to operate on inputs more directly as in your example.
This code uses an extremely quick, dirty, and naive bit manipulation method, but I like working with binary text strings when I'm in a hurry. One more note, this is using the more modern chiseltest (vs old iotesters), but a similar method could be used in iotesters
import chisel3._
import chiseltest._
import chiseltest.experimental.ChiselTestShell
class PassThrough extends Module {
val io = IO(new Bundle {
val in = Input(UInt(32.W))
val out = Output(UInt(32.W))
})
io.out := io.in
}
/** use strings to construct bit mask to clear target range and then or in newbits */
def setBits(
target: BigInt,
topBit: Int,
lowBit: Int,
newBits: BigInt
): BigInt = {
val clearMask = BigInt(
"1" * (target.bitLength.max(
newBits.bitLength
) - topBit) + "0" * (topBit - lowBit + 1) + "1" * lowBit,
radix = 2
)
(target & clearMask) | (newBits << lowBit)
}
// crude verification of setBits
println(setBits(BigInt(31), 2, 1, 2).toString(2))
chiseltest.RawTester.test(new PassThrough) { c =>
c.io.in.poke(40.U)
c.clock.step()
c.io.out.expect(40.U)
val lastIn = c.io.in.peek().litValue()
val newVal = setBits(lastIn, 31, 23, 6)
val bitAddr = (0 to 31).map { x => x % 10 }.reverse.mkString("")
println(s" = $bitAddr")
println(f"lastIn = ${lastIn.toString(2)}%32s")
println(f"newVal = ${newVal.toString(2)}%32s")
c.io.in.poke(newVal.U)
c.clock.step()
c.io.out.expect(newVal.U)
}

How to freely assign values to vec type variables in chisel?

I defined some vec variables.
val r_parameters = Wire(Vec(RANK, UInt(log2Ceil(RANK).W)))
val test0 = Wire(Vec(RANK, UInt(width.W)))
val test1 = Wire(Vec(RANK, UInt(width.W)))
I try to use for loop for assignment.
for (i <- 0 to RANK-1)
{
test0(r_parameters(i)) := test1(i)
}
variable 'r_parameters' is from rom or ram. If parameter 'RANK' is 4, r_parameters has the form as '0 3 2 1' or '0 1 2 3'. Thus all test0 are assigned. But firrtl compiler reports that test0 is not fully initialized.
I think the problem is that the firrtl compiler cannot be sure that every element of test0 has been initialized to something. I have filled out your examples, with values supplied and a couple of stylistic changes to this.
class Wires extends MultiIOModule {
val RANK = 4
val bits = 8
// set to 0, 3, 2, 1
val r_parameters = VecInit(Seq(0, 3, 2, 1).map(_.U) )
val test0 = Wire(Vec(RANK, UInt(bits.W)))
// Give values to test1
val test1 = VecInit(Seq.tabulate(RANK) { i => i.U } )
// Wire test1 into test using the map provided by r_parameters
for (i <- test0.indices) {
test0(r_parameters(i)) := test1(i)
}
}
If you dump the emitted firrtl with
println((new ChiselStage).emitFirrtl(new Wires))
You will see
test0[r_parameters[0]] <= test1[0] #[MemBank.scala 56:28]
test0[r_parameters[1]] <= test1[1] #[MemBank.scala 56:28]
test0[r_parameters[2]] <= test1[2] #[MemBank.scala 56:28]
test0[r_parameters[3]] <= test1[3] #[MemBank.scala 56:28]
Firrtl cannot confirm that r_parameters has exhaustively connected test0.
One important question is do you need to need to have r_parameters be a Vec instead of just a Seq. If you change the r_parameters above to
val r_parameters = Seq(0, 3, 2, 1)
The Module will compile correctly. I suspect this is what you want. If you really need to r_parameters to be a dynamic index and you need to refactor your code. It is possible to add
test0 := DontCare
In front of your loop but I wouldn't recommend it in this case.
Hope this helps, happy chiseling!

Scala: Self-Recursive val in function [duplicate]

Why can't i define a variable recursively in a code block?
scala> {
| val test: Stream[Int] = 1 #:: test
| }
<console>:9: error: forward reference extends over definition of value test
val test: Stream[Int] = 1 #:: test
^
scala> val test: Stream[Int] = 1 #:: test
test: Stream[Int] = Stream(1, ?)
lazy keyword solves this problem, but i can't understand why it works without a code block but throws a compilation error in a code block.
Note that in the REPL
scala> val something = "a value"
is evaluated more or less as follows:
object REPL$1 {
val something = "a value"
}
import REPL$1._
So, any val(or def, etc) is a member of an internal REPL helper object.
Now the point is that classes (and objects) allow forward references on their members:
object ForwardTest {
def x = y // val x would also compile but with a more confusing result
val y = 2
}
ForwardTest.x == 2
This is not true for vals inside a block. In a block everything must be defined in linear order. Thus vals are no members anymore but plain variables (or values, resp.). The following does not compile either:
def plainMethod = { // could as well be a simple block
def x = y
val y = 2
x
}
<console>: error: forward reference extends over definition of value y
def x = y
^
It is not recursion which makes the difference. The difference is that classes and objects allow forward references, whereas blocks do not.
I'll add that when you write:
object O {
val x = y
val y = 0
}
You are actually writing this:
object O {
val x = this.y
val y = 0
}
That little this is what is missing when you declare this stuff inside a definition.
The reason for this behavior depends on different val initialization times. If you type val x = 5 directly to the REPL, x becomes a member of an object, which values can be initialized with a default value (null, 0, 0.0, false). In contrast, values in a block can not initialized by default values.
This tends to different behavior:
scala> class X { val x = y+1; val y = 10 }
defined class X
scala> (new X).x
res17: Int = 1
scala> { val x = y+1; val y = 10; x } // compiles only with 2.9.0
res20: Int = 11
In Scala 2.10 the last example does not compile anymore. In 2.9.0 the values are reordered by the compiler to get it to compile. There is a bug report which describes the different initialization times.
I'd like to add that a Scala Worksheet in the Eclipse-based Scala-IDE (v4.0.0) does not behave like the REPL as one might expect (e.g. https://github.com/scala-ide/scala-worksheet/wiki/Getting-Started says "Worksheets are like a REPL session on steroids") in this respect, but rather like the definition of one long method: That is, forward referencing val definitions (including recursive val definitions) in a worksheet must be made members of some object or class.

Passing a function to an argument in Scala

Is there any way to do something like argument.<keyword>(function) in Scala?
For example:
[1,2,3].supply(myFunc) yielding 6 if myFunc were the summation function.
It just seems easier to chain functions if I were able to do this, instead of calculating something and 'wrapping it' into an argument for a function call.
You can define it yourself if you want. It's frequently called the "pipe operator":
class AnyWrapper[A](wrapped: A) {
def |>[B](f: A => B) = f(wrapped)
}
implicit def extendAny[A](wrapped: A): AnyWrapper[A] = new AnyWrapper(wrapped)
Then:
def plus1(i: Int) = i + 1
val fortyTwo = 41 |> plus1
Do you mean something like this:
val sum = { (a: Int, b: Int) => a + b }
List(1, 2, 3).reduceLeft(sum)

Functional Programming: Does a list only contain unique items?

I'm having an unsorted list and want to know, whether all items in it are unique.
My naive approach would be val l = List(1,2,3,4,3)
def isUniqueList(l: List[Int]) = (new HashSet()++l).size == l.size
Basically, I'm checking whether a Set containing all elements of the list has the same size (since an item appearing twice in the original list will only appear once in the set), but I'm not sure whether this is the ideal solution for this problem.
Edit:
I benchmarked the 3 most popular solutions, l==l.distinct, l.size==l.distinct.size and Alexey's HashSet-based solution.
Each function was run 1000 times with a unique list of 10 items, a unique list of 10000 items and the same lists with one item appearing in the third quarter copied to the middle of the list. Before each run, each function got called 1000 times to warm up the JIT, the whole benchmark was run 5 times before the times were taken with System.currentTimeMillis.
The machine was a C2D P8400 (2.26 GHz) with 3GB RAM, the java version was the OpenJDK 64bit server VM (1.6.0.20). The java args were -Xmx1536M -Xms512M
The results:
l.size==l.distinct.size (3, 5471, 2, 6492)
l==l.distinct (3, 5601, 2, 6054)
Alexey's HashSet (2, 1590, 3, 781)
The results with larger objects (Strings from 1KB to 5KB):
l.size==l.distinct.size MutableList(4, 5566, 7, 6506)
l==l.distinct MutableList(4, 5926, 3, 6075)
Alexey's HashSet MutableList(2, 2341, 3, 784)
The solution using HashSets is definitely the fastest, and as he already pointed out using .size doesn't make a major difference.
Here is the fastest purely functional solution I can think of:
def isUniqueList(l: List[T]) = isUniqueList1(l, new HashSet[T])
#tailrec
def isUniqueList1(l: List[T], s: Set[T]) = l match {
case Nil => true
case (h :: t) => if (s(h)) false else isUniqueList1(t, s + h)
}
This should be faster, but uses mutable data structure (based on the distinct implementation given by Vasil Remeniuk):
def isUniqueList(l: List[T]): Boolean = {
val seen = mutable.HashSet[A]()
for (x <- this) {
if (seen(x)) {
return false
}
else {
seen += x
}
}
true
}
And here is the simplest (equivalent to yours):
def isUniqueList(l: List[T]) = l.toSet.size == l.size
I would simply use distinct method:
scala> val l = List(1,2,3,4,3)
l: List[Int] = List(1, 2, 3, 4, 3)
scala> l.distinct.size == l.size
res2: Boolean = false
ADD: Standard distinct implementation (from scala.collection.SeqLike) uses mutable HashSet, to find duplicate elements:
def distinct: Repr = {
val b = newBuilder
val seen = mutable.HashSet[A]()
for (x <- this) {
if (!seen(x)) {
b += x
seen += x
}
}
b.result
}
A more efficient method would be to attempt to find a dupe; this would return more quickly if one were found:
var dupes : Set[A] = Set.empty
def isDupe(a : A) = if (dupes(a)) true else { dupes += a; false }
//then
l exists isDupe