How to add elements in Vec like a binary tree's leaf nodes? - chisel

assuming n = 2^x elements in Vec,
adding elements in Vec using
vec.reduce(_ +& _)
will end up with element width = w + 2^x - 1
if adding them for every two elements like a tree, the width will be w + x
seems
vec.par.reduce(_ +& _)
works for 4 elements, but not for 8 or 16.
Any workaround?

I suggest you take a look at the experimental Interval type in chisel3. There's some limited documentation here. Intervals were designed for just this situation. You shouldn't even have to change everything, just map the elements of your Vec to Intervals and then reduce them.

chisel3.Vec has a reduceTree method that will do what you want:
class Example extends MultiIOModule {
val in = IO(Input(Vec(8, UInt(8.W))))
val out = IO(Output(UInt())) // Infers width to be 11
out := in.reduceTree(_ +& _)
}
Scastie link: https://scastie.scala-lang.org/rhm4je13T0ykEtRS7P7mfQ
Also see the Vec API docs: https://www.chisel-lang.org/api/latest/chisel3/Vec.html

Related

Difference between . and 1 in glm

I want to perform a regression and first of all I want to test if my nullmodel is significant.
So if not, I wont be able to perform the stepwise introduction according to AIC.
So I did the following:
m0 <- glm(Y~ 1, data = Data, family = binomial)
summary(m0)
So I have seen on the internet that some people use this code:
model <- glm(Y ~ .,data = Data, family=binomial)
summary(model)
What I want to know is whats the difference between the dot (.) and the 1.
Thank you :)
The Y is the dependent variable the right is the independent variable, the . is short hand for all the other variables
Y ~ val means model Y with val
Y ~ . means the model against all the other variables
Meaning of dot in lm(y~.) in R

Ocaml take function

i am trying to make a function that returns the value of first k elements in a list. This is not working. I do not know why.
Can someone help?
This is the tl function -
let tl j = match j with
| [] -> []
| x :: xs -> xs;;
This is the real take function-
let rec take k xs = function
| [] -> failwith "take"
| x :: xs -> if k = List.length ([x] # xs) then [x] # xs
else [x] # take List.length xs (tl(List.rev.xs))
The cause for the message is that you left out a pair of parentheses, so you're trying to pass List.length as the first parameter to take.
Another problem is that you're defining a function with three parameters – your definition says that take k xs returns a function that takes a list argument (which is unnamed).
A third problem is take (List.length xs) (tl(List.rev xs)).
This attempts to take one more element than there are from the tail of xs (and, for some reason, in reverse).
So I'm going to rewrite it completely.
First of all, you should not use List.length for this.
(List.length is almost never a good solution.)
You only need to care about whether the list is empty or not, it doesn't matter how long it is.
Now, a more formal definition:
take k xs is
if k is 0, it's the empty list
otherwise, if xs is the empty list, it's an error
otherwise, it is the list whose first element is the head of xs, and whose tail is the result of taking k - 1 elements from the tail of xs.
That is,
let rec take k xs = match k with
| 0 -> []
| k -> match xs with
| [] -> failwith "take"
| y::ys -> y :: (take (k - 1) ys)
Your function accepts an integer n, and takes n elements from a list list, which is the list which contains the n first elements of list.
So your signature is likely to be:
int -> 'a list -> 'a list = <fun>
You probably already can guess that the function is going to be defined recursively, so you can already write the definition of your function like this:
let rec take n list = ...
You have to build a list, but let's first consider three major classes of values for n:
n = 0 : just return an empty list
n > 0 : take one element and recurse with n - 1
n < 0 : The negative case is easy to miss, but if you are not cautious, you can easily enter an infinite recursion at runtime with invalid inputs. Here, fortunately, we are going to use an exception and make things terminate down the recursive chain (that's what happens in moldbino's answer, for example), but other functions might not behave as nicely.
Some implementations of take, when given a negative numbers, try to be useful and takes n elements from the end of the list.
Here we will simply treat any n that is not strictly positive as-if if was null.
Null or negative N
When we take zero elements from a list, that means that we return the empty list:
let rec take n list =
if n > 0
then ...
else [];;
Positive N
Now, we consider the case where we take n > 0 elements from a list.
Following the recursive definition of lists, we have to consider each possible kind of lists, namely the empty list and non-empty lists.
let rec take n list =
if n > 0
then
match list with
| [] -> ...
| x :: xs -> ...
else [];;
What happens when we want to take n > 0 elements from an empty list?
We fail.
let rec take n list =
if n > 0 then
match list with
| [] -> failwith "Not enough elements in list"
| x :: xs -> ...
else [];;
Now, the general case of recursion. We have a non-empty list, and n > 0, so we know that we can take at least one element from the list.
This value is x, which forms the head of the list we want to return. The tail of the list is the one made of the n-1 elements of xs, which is easily computed by take itself:
let rec take n list =
if n > 0 then
match list with
| [] -> failwith "Not enough elements in list"
| x :: xs -> x :: (take (n - 1) xs)
else [];;
Your immediate problem is that you need parentheses around (List.length xs). The code also treats an empty input list as an error in all cases, which is not correct. An empty list is a legitimate input if the desired length k is 0.
Update
You also have one extra parameter in your definition. If you say this:
let myfun k xs = function ...
the function myfun has 3 parameters. The first two are named k and xs and the third is implicitly part of the function expression.
The quick fix is just to remove xs.
I think you might be asking for the wrong number of elements in your recursive call to take. Something to look at anyway.

Haskell: "how much" of a type should functions receive? and avoiding complete "reconstruction"

I've got these data types:
data PointPlus = PointPlus
{ coords :: Point
, velocity :: Vector
} deriving (Eq)
data BodyGeo = BodyGeo
{ pointPlus :: PointPlus
, size :: Point
} deriving (Eq)
data Body = Body
{ geo :: BodyGeo
, pict :: Color
} deriving (Eq)
It's the base datatype for characters, enemies, objects, etc. in my game (well, I just have two rectangles as the player and the ground right now :p).
When a key, the characters moves right, left or jumps by changing its velocity. Moving is done by adding the velocity to the coords. Currently, it's written as follows:
move (PointPlus (x, y) (xi, yi)) = PointPlus (x + xi, y + yi) (xi, yi)
I'm just taking the PointPlus part of my Body and not the entire Body, otherwise it would be:
move (Body (BodyGeo (PointPlus (x, y) (xi, yi)) wh) col) = (Body (BodyGeo (PointPlus (x + xi, y + yi) (xi, yi)) wh) col)
Is the first version of move better? Anyway, if move only changes PointPlus, there must be another function that calls it inside a new Body. I explain: there's a function update which is called to update the game state; it is passed the current game state, a single Body for now, and returns the updated Body.
update (Body (BodyGeo (PointPlus xy (xi, yi)) wh) pict) = (Body (BodyGeo (move (PointPlus xy (xi, yi))) wh) pict)
That tickles me. Everything is kept the same within Body except the PointPlus. Is there a way to avoid this complete "reconstruction" by hand? Like in:
update body = backInBody $ move $ pointPlus body
Without having to define backInBody, of course.
You're looking for "lenses". There are several different packages for lenses; here is a good summary of them.
My understanding is that a lens on a data type a for some field b provides two operations: a way to get the value of b and a way to get a new a with a different value of b. So you would just use a lens to work with the deeply nested PointPlus.
The lens packages provide useful functions for working with lenses as well as ways of generating lenses automatically (with template Haskell) which could be very convenient.
I think they are worth looking into for your project, especially because you are likely to encounter similar problems with nesting in other places thanks to the structure of your data types.

Languages that take chaining to the extreme?

So, I was just thinking about how cool chaining is and how it makes things easier to read. With a lot of languages, when applying a bunch of functions to a variable, you'd write something like this:
i(h(g(f(x))))
And you have to read it from right-to-left or inner-most to outer-most. You apply f first, then g, and so forth. But if it were chained, it would look more like
x|f|g|h|i
And you could read it like a normal human being. So, my question is, there has to be some languages that do it that way, what are they? Is that what these fancy-pants functional programming languages do?
Because of this, I usually end up creating a whole bunch of temp variables so that I can split it onto separate lines and make it more readable:
a = f(x)
b = g(a)
c = h(b)
what_i_really_wanted_all_along = i(c)
Where's with my magical language, you could still split it onto different lines, if they're getting too long, without needing intervening variables:
x | f
| g
| h
| i
Yes, with F# you have a pipeline operator |> (also called forward pipe operator, and you have a backward pipe <|).
You write it like: x |> f |> g |> h |> i
Check this blog post that gives a good idea of real life usage.
It's not exclusive to functional programming, though it probably best implemented in functional languages, since the whole concept of function composition is squarely in the functional programming's domain.
For one thing, any language with object-oriented bent has chaining for methods which return an instance of the class:
obj.method1().method2().method3(); // JavaScript
MyClass->new()->f()->g()->i(); # Perl
Alternately, the most famous yet the least "programming-language" example of this chaining pattern would be something completely non-OO and non-functional ... you guessed it, pipes in Unix. As in, ls | cut -c1-4 | sort -n. Since shell programming is considered a language, I say it's a perfectly valid example.
Well, you can do this in JavaScript and its relatives:
function compose()
{
var funcs = Array.prototype.slice.call(arguments);
return function(x)
{
var i = 0, len = funcs.length;
while(i < len)
{
x = funcs[i].call(null, x);
++i;
}
return x;
}
}
function doubleIt(x) { print('Doubling...'); return x * 2; }
function addTwo(x) { print('Adding 2...'); return x + 2; }
function tripleIt(x) { print('Tripling...'); return x * 3; }
var theAnswer = compose(doubleIt, addTwo, tripleIt)( 6 );
print( 'The answer is: ' + theAnswer );
// Prints:
// Doubling...
// Adding 2...
// Tripling...
// The answer is: 42
As you can see, the functions read left-to-right and neither the object nor the functions need any special implementation. The secret is all in compose.
What you're describing is essentially the Fluent Interface pattern.
Wikipedia has a good example from a number of languages:
http://en.wikipedia.org/wiki/Fluent_interface
And Martin Fowler has his write up here:
http://www.martinfowler.com/bliki/FluentInterface.html
As DVK points out - any OO language where a method can return an instance of the class it belongs to can provide this functionality.
C# extension methods accomplish something very close to your magical language, if a little less concisely:
x.f()
.g()
.h()
.i();
Where the methods are declared thus:
static class Extensions
{
static T f<T>(this T x) { return x; }
static T g<T>(this T x) { return x; }
...
}
Linq uses this very extensively.
Haskell. The following three examples are equivalent:
i(h(g(f(x)))) (Nested function calls)
x & f & g & h & i (Left-to-right chaining as requested)
(i . h . g . f)(x) (Function composition, which is more common in Haskell)
http://www.haskell.org/haskellwiki/Function_composition
http://en.wikipedia.org/wiki/Function_composition_(computer_science)
I am not suggesting you could use Mathematica if you don't do some math usually, but it certainly is flexible enough for supporting Postfix notation. In fact, you may define your own notation, but let's keep with Postfix for simplicity.
You may enter:
Postfix[Sin[x]]
To get
x // Sin
Which translates to Postfix notation. Or if you have a deeper expression:
MapAll[Postfix, Cos[Sin[x]]]
To get:
(Postfix[x]//Sin)//Cos
Where you may see Postfix[x] first, as for Mathematica x is an expression to be evaluated later.
Conversely, you may input:
x // Sin // Cos
To get of course
Cos[Sin[x]]
Or you can use an idiom very frequently used, use Postfix in Postfix form:
Cos[x] // Postfix
To get
x // Cos
HTH!
BTW:
As an answer to Where's with my magical language,? , see this:
(x//Sin
// Cos
// Exp
// Myfunct)
gives
Myfunct[E^Cos[Sin[x]]]
PS: As an excercise to the readers :) ... How to do this for functions that take n vars?
As has been previously mentioned, Haskell supports function composition, as follows:
(i . h . g . f) x, which is equivalent to: i(h(g(f(x))))
This is the standard order of operations for function composition in mathematics. Some people still consider this to be backward, however. Without getting too much into a debate over which approach is better, I would like to point out that you can easily define the flipped composition operator:
infixr 1 >>>, <<<
(<<<) = (.) -- regular function composition
(>>>) = flip (.) -- flipped function composition
(f >>> g >>> h >>> i) x
-- or --
(i <<< h <<< g <<< f) x
This is the notation used by the standard library Control.Category. (Although the actual type signature is generalized and works on other things besides functions). If you're still bothered by the parameter being at the end, you can also use a variant of the function application operator:
infixr 0 $
infixl 0 #
f $ x = f x -- regular function application
(%) = flip ($) -- flipped function application
i $ h $ g $ f $ x
-- or --
x % f % g % h % i
Which is close to the syntax you want. To my knowledge, % is NOT a built-in operator in Haskell, but $ is. I've glossed over the infix bits. If you're curious, thats a technicality that makes the above code parse as:
(((x % f) % g) % h) % i -- intended
and not:
x % (f % (g % (h % i))) -- parse error (which then leads to type error)

Best line equation to use for computational geometry

I'm looking to write a little comp-geom library, in Ruby.
I'm about to write the code for lines, and was wondering which line equation I should use:
ax + by + c = 0
r + tv (where r and v are vectors)
Thanks.
If using the classical equations is not a requirement, I'd suggest an array of four co-ordinates: xStart, yStart, xEnd and yEnd.
In case you need to make the line position dynamic, you could use an array of two parameters: alpha and radius. The former represents radial rotation relative to the horizontal axis and the latter is the length of line.
Yet another option would be vectors in the form of (X;Y).
Samples in C:
int endpointsLine[4] = {0, 0, 30, 40};
double radialLine[2] = {5.35589, 50};
int vectorLine[2] = {30, 40};
The "endpoints" format is fully compatible with modern line-drawing algorithms, such as Xiaolin Wu's line algorithm and Bresenham's line algorithm but it represents specific screen co-ordinates which is not the case with "radial" and "vector" format.