In chisel, How to generate serval Module with different parameter? - scala

I have a Module monit which has an parameter threshold , then I want to generate serval(e.g.8) Module monit in the wrapper with different threshold . But when I use
val monits = Seq.fill(8)(Module(new monit(32)))
to create 8 modules monit, they all have same threshold, how can I deliver different threshold parameter?

Maybe something like this?
val thresholds = Seq(1,2,3,4,5,6,7,8)
val monits = thresholds.map(th => Module(new monit(th)) )
I typed this on my phone and have not tested the code, but should give an idea about using scala collections and map for the purpose.

Related

How to define a infinite Lazy List using a given function or property in Scala?

I recently was seeing an advanced Scala course in Rock the JVM and, in one lesson, Daniel purposed to create a set using propertys (functions going from A to Boolean), the implementation of this Set can be found here.
For example, he was able to create a set "containing" all the naturals by doing this:
val naturals = PBSet[Int](_ => true)
Then he could verify if an input was contained inside that set by doing naturals.contains(input).
My question is, is there any way to accomplish this using Lazy Lists or even better, Lazy Vectors or Lazy Maps?
For instance, given a fibonacci(n) function that returns the nth Fibonacci number, a lazy list containing all the posible outputs for that function would look like something like this:
val allFibonacciNumbers: LazyList[Long] = LazyList.generate(n => fibonacci(n))
I know something similiar could be done by doing this:
val allFibonacciNumbersV2: LazyList[Long] = LazyList.iterate(0L)(n => n + 1).map(n => fibonacci(n))
The problem of that implementation is the start value of the iterate function: It is not going to give all the possible outputs of any function, just the ones after that.
So, how could such a task be accomplished using a combination of the Porperty based Set and the Lazy List? Or even better, with a Lazy Vector or Lazy Map?
I couldn't find anything similar, the closest I could find was something called property based test but that's about it.
Thank you for the immense help and for reading my question. Have a great day!
Well, there is no "LazyMap" out of the box, but it is rather trivial to just roll your own.
Your comments sound like you already know how to compute Fibonacci with a LazyList, from there, you just need to memoize the result:
object FF {
val fm = mutable.Map.empty[Int, BigInt]
val fib: LazyList[BigInt] = BigInt(0) #:: BigInt(1) #::
fib.zip(fib.tail).map(p => p._1 + p._2)
def apply(n: Int) = fm.getOrElseUpdate(n, fib(n))
}
Now, things like FF(100) are linear the first time, and constant time after that.
If you do FF(100), and then FF(99), that second call is still linear for the first time though. Technically, it could be optimized to be constant time too, because fib(99) is already available, but I don't think it's worth the trouble ... and extra storage.

Define a function or a variable in scala that starts with a number

Is it possible to write a val or a def that starts with a number? I know scala vals and defs can have pretty crazy characters in them. I'd like to make some constants like:
val 512MB = 536870912
But not sure if this is possible.
You can use just about anything in a value name if you use backticks:
val `512MB` = 536870912
As #Jack Leow mentioned, you can use any name with the backticks, but you'll have to use them all the time. Did you consider to use DSL in-place where you need these consts? In this case you can write something like this in your code:
val mySize = 512 MB
Please check this thread for more details how you can achieve that.

Unit test to check retrievals from config file

In a spark project we use Typesafe Config. We have a big config file with some (necessary) redundancy. It is quite easy to refer the wrong branch of the config json and sometimes the error slips to production code.
I need to verify that all the calls of config.getString(x) with x literal will not fail for a given config file.
I'd like to write a unit test that checks every string used in my application to obtain a config value.
A possible solution we found is to preload all the config values to a case class, so
val rawPath = config.getString("comp1.data.files.rawData")
val coresNumber = config.getLong("comp1.setup.cores")
would become
case class ConfigData(rawPath:String, coresNumber:Long)
def initConfig():ConfigData ={
val rawPath = config.getString("comp1.data.files.rawData")
val coresNumber = config.getLong("comp1.setup.cores")
ConfigData(rawPat,coresNumber)
}
val conf = initConfig()
val rawPath = conf.rawPath
val coresNumner = conf.coresNumber
and then simply call initData() to test for config load errors.
I've also thought of using scala reflection but I'd need to find all the places in my code where config.getString(x) is called and then obtain the x to test their existence in the config file, but I can't find a way to get all the instances of a method call and create a test on the parameter.
Is there anything I haven't thought of?
One solution is to provide the configuration in a Singleton, which you initialise when starting the server - so the Server starts only if the configuration is correct. Or run the configurations in Unit Tests.
In this Singleton you load your Configuration in single values or case classes depending on amount of values.
We use pureconfig which makes it pretty simple to map the configuration directly into case classes.
Here is an Example without Pure Script: DemoAdapterContext and AdaptersContext.
Let me know if you need more infos.

Avoid testing duplicate values with ScalaTest forAll

I'm playing with property-based testing on ScalaTest and I had the following code:
val myStrings = Gen.oneOf("hi", "hello")
forAll(myStrings) { s: String =>
println(s"String tested: $s")
}
When I run the forAll code, I've noticed that the same value is tried more than once, e.g.
String tested: hi
String tested: hello
String tested: hi
String tested: hello
String tested: hi
String tested: hello
...
I was wondering if there is a way for, given the code above, for each value in oneOf to be tried only once. In other words, to get ScalaTest not to use the same value twice.
Even if I used other generators, such as Gen.alphaStr, I'd like to find a way to avoid testing the same String twice. The reason I'm interested in doing this is because each test runs against a server running in a different process, and hence there's a bit of cost involved, so I'd like to avoid testing the same thing twice.
What you're trying to do is seems to be against scalacheck ideology(see Note1); however it's kind of possible (with high probability) by reducing the number of samples:
scala> forAll(oneOf("a", "b")){i => println(i); true}.check(Test.Parameters.default.withMinSuccessfulTests(2))
a
b
+ OK, passed 2 tests.
Note that you can still get aa/bb sometimes, as scala-check is built on randomness and statistical approach. If you need to always check all combinations - you probably don't need scala-check:
scala> assert(Set("a", "b").forall(_ => true))
Basically Gen allows you to create an infinite collection that represents a distribution of input values. The more values you generate - the better sampling you get. So if you have N possible states, you can't guarantee that they won't repeat in an infinite collection.
The only way to do exactly what you want is to explicitly check for duplicates before calling the service. You can use something like Option(ConcurrentHashMap.putIfAbscent(value, value)).isEmpty for that. Keep in mind it is a risk of OOM so be careful to take care of the amount of generated values and maybe even add an explicit check.
Note1) What scalacheck is needed for reducing number of combinations from maximum (which is more than 100) to some value that still gives you a good check. So scalacheck is useful when a set of possible inputs is really huge. And in that case the probability of repetitions is really small
P.S.
Talking about oneOf (from scaladoc):
def oneOf[T](t0: T, t1: T, tn: T*): Gen[T]
Picks a random value from a list
See also (examples are a bit outdated): How can I reduce the number of test cases ScalaCheck generates?
I would aim to increase the entropy of values. Using random sentences will increase it a lot, although not (theoretically) fixing the issue.
val genWord = Gen.onOf("hi", "hello")
def sentanceOf(words: Int): Gen[String] = {
Gen.listOfN(words, genWord).map(_.mkString(" ")
}

How can I generate my own ScalaSig?

I've dynamically defined a Scala class, but in order to use it "properly" it needs to have a ScalaSig.
So, how might I generate a ScalaSig outside of normal compilation? Perhaps from a tree? Maybe like:
val tb = runtimeMirror(getClass.getClassLoader).mkToolBox()
val classDef = """class MyRecord(x: String)"""
val tree = showRaw(tb.parse(classDef))
But where does the pickler come in?
Thanks for any advice
-Julian
Artisanal-Pickle-Maker will reproduce a Scala pickled signature byte-for-byte (see restrictions).
Tapping into the compiler's pickler phase, as well as reuse of the Pickler's code, proved too challenging, so instead I used PickleBuffer, ShowPickled and a whole lotta diff -y to figure out how to generate arbitrary pickled Scala sigs.