How to convert from Uint to Int - chisel

I would like to use Log2() for bit width extraction in IO. Which Log2() is Uint, but bit-width declaration probably needs Int type. So, I want to convert (cast) from Uint to Int.
I tried to do as follow in IO;
val hoge = Output(Uint(Log2(BitWidth).W))
Then this produces an error of type-mismatch. I could not find UInt to Int conversion. How to do it?

Chisel has chisel3.util.log2Ceil(i: Int) which returns the number of bits required to hold i values. Your example has a typo Uint instead of UInt which maybe causing problems. I'm not sure what BitWidth in your example is? Is it a class or an Int, if it's an Int it would be better to use the scala convention for lowercase beginnings for variable names. If you have a val x = UInt(8.W) and you would like to use the width of x in an IO declaration it would look like
val a = IO(Input(chiselTypeOf(x)))
I hope this helps

val hoge = Output(UInt((Log2Up(BitWidth : Int) : Int).W))
I am not sure if you can use just Log2, try using Log2Up or Log2Down with the syntax as shown above. I guess this should work, let me know if this fixes the error and yeah use UInt instead of Uint

If you're looking strictly to cast, UInts have the asSInt method. See:

Related

Is a function just a type like any other type? [duplicate]

When I define a custom type, it seems that the type of the underlying type makes a difference about whether I can pass it to a function as is or I need to convert it.
Question is:
Why does RuneFunc and StringMap work, but not Integer?
https://play.golang.org/p/buKNkrg5y-
package main
type RuneFunc func(rune) rune
type Integer int
type StringMap map[string]string
func main() {
//m := make(StringMap)
//mf(m)
var i Integer = 5
nf(i)
//var f func(rune) rune
//ff(f)
}
func mf(i map[string]string) {
}
func ff(i func(rune)rune) {
}
func nf(i int) {
}
Here, when I run this function called nf with Integer it complains although int is the underlying type. But when I call mf or ff they run successfully.
Integer and int
int and your new type Integer are 2 different, distinct types. Where Integer is expected, you have to pass a value of type Integer.
If you have an Integer value, you may use a simple type conversion to make it a value of type int, because the underlying type of Integer is int:
var i Integer = 5
nf(int(i))
What may be confusing and interesting at the same time is that you are allowed to pass an untyped constant without conversion:
nf(5)
Try these on the Go Playground.
The reason for this is in the Spec: Assignability:
A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
[...]
x is an untyped constant representable by a value of type T.
5 is an untyped constant which is representable by a value of type int because the untyped constant 5 has a default type int, so it is representable by a value of type Integer (which has the same default type).
If you check the other assignability rules (not included in above quotation), none of them match the case where you attempt to pass a value of Integer for the parameter of type int, so that's not allowed.
See related question: Golang: Creating a Constant Type and Restricting the Type's Values
RuneFunc and func(rune) rune
The difference between this case and the previous one (Integer and int) is that int is a named type and func(rune) rune is not.
And there's an assignability rule which allows this:
x's type V and T have identical underlying types and at least one of V or T is not a named type.
So in this case:
var f RuneFunc
ff(f)
f is a named type, but the parameter type of ff() is func(rune) rune which is unnamed, so the assignment is allowed.
Go has a strict type system. Just because your type is merely an alias for int doesn't mean you can interchange the two freely, you'll still have to do a type conversion. Below is a working version of your main, here's the code on play ground: https://play.golang.org/p/BDTXnnG9Lg

how do I autoconvert a struct* to a dict?

mystruct.pxd
ctypedef struct foo:
pass
ctypedef struct myStruct:
int field1
int field2
foo* field3
mystruct.pyx
class MyStruct:
cdef myStruct* _ptr
def __cinit__(self):
self._ptr = create_myStruct()
def __getattr__(self, key):
if key in self._ptr[0]:
return self._ptr[0][key]
__getattr__ does not compile with cython. Attempting to index non-array type 'myStruct'
Removing the [0] results in a compiler crash.
Attempts to do:
def get_dict(self):
return self._ptr # cannot convert 'myStruct *' to Python object
return self._ptr[0] # cannot convert 'myStruct' to Python object
These structs have many fields that I need to access as properties. Writing basic #property wrappers is adding a lot of clutter to the file so I'd like to be able to use a simple getaddr instead. Any thought?
UPDATE: changed type of field3
It seems the problem is with foo* field3 since foo is a custom struct and not a primitive type (numeric, char*) autoconversion will not work. There does not appear to be a way to fix this directly. I have two workarounds:
Change the type of field3 to unsigned int (or whatever your pointer size is) and cast to foo* when you need to access the sub-structure. This is not a very nice workaround but if your members are really opaque types and not accessible structs, it works just fine.
Write something to explicitly convert to a dict.
This is what I ended up doing. It's another repetition of the field names but it can be easily created with copy-paste-modify
def to_dict(self):
return {'field1':self._ptr.field1,
'field2':self._ptr.field2,
'field3':FooWrapper().from_ptr(self._ptr.field3) # or an int if opaque
}
cdef class FooWrapper:
cdef foo* _ptr
def from_ptr(self, ptr):
assert(ptr is not NULL)
self._ptr = ptr
return self

why declaration of methods in different style different results in scala

Below are two methods that are declared in different style. Both are doing the same work. I am wondering, why
different syntax is required to check type of function (yellow
block)
different syntax is required to call function (green block)
declaration of both methods on scala repl gives different results
(red block)
Also, please suggest, which one is the preferred way to declare
methods or are there any special use cases for both the styles of
method declaration?
Edit 1:
Below are the commands from screenshot :-
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def add(x:Int, y :Int): Int = {x+y}
add: (x: Int, y: Int)Int
scala> def sum = (x:Int, y:Int) => {x+y}
sum: (Int, Int) => Int
scala> :t add
<console>:12: error: missing arguments for method add;
follow this method with `_' if you want to treat it as a partially applied function
add
^
scala> :t add(_, _)
(Int, Int) => Int
scala> :t sum
(Int, Int) => Int
scala> add
<console>:12: error: missing arguments for method add;
follow this method with `_' if you want to treat it as a partially applied function
add
^
scala> add(_, _)
res1: (Int, Int) => Int = <function2>
scala> sum
res2: (Int, Int) => Int = <function2>
Edit 2:
#Shadowlands
i have read on dzone, that states "when a function is expected but a method is provided, it will be automatically converted into a function. This is called the ETA expansion.".
Now, if ETA takes care to convert your methods to function. Is it really required to use sum style, because it looks like an additional overhead of Function<> object.
Simply put, add is a function that takes two Int arguments and returns an Int result, while sum is a 0-argument function that returns a new function that, in turn, takes two Int arguments and returns an Int result. Indeed, sum could readily be defined as:
def sum = add _
As to which way to define your functions, this depends on how it is to be used. Generally, use the add style most of the time, as it is easier to understand and work with. If, however, you will be passing the function as an argument to another function, then the sum-style formulation can be more convenient and may convey more of your intent on how the function is expected to be used.
This is how REPL is implemented. The code that you type is wrapped in object. Thus your def add becomes method of this object, while def sum is a method that returns Function. When you are addressing add like this: add(_, _) you are addressing method, while when you are addressing sum as sum you are addressing result of sum's execution, which is function.
Differences between methods and functions are described here.
PS. Try to check the type of sum _

scala implicit class method type mismatch in reduce vs non-implicit method with function currying

Problem:
Something about implicit class, confuses reduce().
When inside implicit class, compiler complains on reduce() second parameter.
but when same code is inside non-implicit method it compiles and works fine.
What am I missing about implicit classes?
Code:
object ImpliCurri {
implicit class MySeq[Int](val l: Seq[Int]) {
//not compiling
final def mapSum(f:Int=>Int):Int = {
l.map(x=>f(x)).reduce(_+_)
//compile error on reduce: Type mismatch. Expected String, fount Int
}
}
// works fine
def mySum(l:Seq[Int], f:Int=>Int):Int = {
l.map(x=>f(x)).reduce(_+_)
// compiles and works no issues
}
}
You need to get rid of the type parameter Int. Int in the case of the implicit class is not actually the type Int, but instead it's a free type parameter that's shadowing the name of Int.
The reason for the cryptic compiler error is that the compiler is inferring the type Any from the lambda _ + _ (since the type parameter could be anything), and assuming the + will come from a toString on type Any. If you replace Int with T in the class declaration, you'll see the error is the same.
This will work:
implicit class MySeq(val l: Seq[Int]) {
final def mapSum(f: Int => Int): Int = {
l.map(x => f(x)).reduce(_ + _)
}
}
It doesn't actually have anything to do with implicits. You get the same error if it's just a regular class.
The reason is that you have declared a generic type: MySeq[Int] that just happens to be called Int. So when you say f: Int => Int you think "Oh, that's an integer" and the compiler thinks, "Oh, that means you could fill in any type there!". (Replace all your Ints with A and it would work the same.)
Now the compiler is in a bind. What + can you apply to any pair of types? Well, you can convert anything to a String, and + is defined on a String. So you get a very misleading error message when the compiler realizes that this approach won't work.
Just drop the [Int] and all your Ints will actually mean what you think they mean, and the implicit class version will work fine.
Replace MySeq[Int](val l: Seq[Int]) with MySeq(val l: Seq[Int]).
Explanation of the compiler message:
The MySeq[Int] part defines an abstract type parameter for class MySeq named Int, which is (automatically) a subclass of Any and shadows the actual scala.Int. Then the compiler tries to call + method of an instance of Any. It sees a declaration of an implicit class scala.Predef.any2stringadd, which has a method with signature def +(other: String): String, so the compiler thinks the second parameter to + should be a String.

Function evaluation

In this question Invoking function which accept functions as parameters is this also a valid explanation of why the code does not compile?
funParam(3) is a valid invocation but fun(funParam(3)) is not. funParam(3) is not evaluated until compilation so the compiler cannot accept this as a valid parameter.
I think I'm confused as it's common practice to pass parameters to functions pre compilation but it is not valid to pass functions which contain parameters to functions pre compilation?
I think you may be confusing a couple concepts.
It's worth thinking about why a function might take another function as a parameter. Given fun: (Int => Int) => Int (a function that takes a function of Int => Int as a parameter and returns an Int), presumably, fun is planning to pass an Int to its argument, and return some modified version of the result. This pattern is used frequently in functional programming, like when we pass functions to map or reduce that operate on values inside a collection. The argument of type Int => Int to fun is essentially a calculation with a "hole" in it, and it's counting on fun or some other operation to provide the Int it needs to be fully evaluated.
funParam(3) doesn't have any unspecified variables, and it will be evaluated immediately whenever it's referred to. That's why the type of funParam(3) is Int. Sure, funParam itself is Int => Int, but since you've given it the Int parameter 3, the type of the whole expression is just the return type: Int.
Given
def funParam(i: Int): Int = ...
You can treat the methodfunParam as a function with type Int => Int
But funParam(3) is not a function, it is a concrete value--an Int, and therefore not Int => Int
So you cannot pass an Int to a method that is expecting Int => Int.
The reason is because fun expects Int => Int as an argument, but funParam(3) is not of that type. Its type is Int.