I have a strange error in Verilog RTL compilation. I have 2 defines and a concatenation of them gives error.
`define ARRAY1 = 3'b001;
`define ARRAY2 = 3'b011;
[...]
next_state = {`ARRAY1,`ARRAY2};
xmvlog: *E,ILLPRI (./../rtl/LVDS_ctrl_phy.v,271|37): illegal expression primary [4.2(IEEE)].
(`define macro: ARRAY1 [./../rtl/LVDS_ctrl_phy.v line 1], file: ./../rtl/LVDS_ctrl_phy.v line 271)
next_state = {`ARRAY1,`ARRAY2};
Since define is merely a text substitution, this shouldn't give error, right?
But, if I substitute with the corresponding text
next_state = {3'b001,3'b011};
this does not give an error.
Do you have any idea why this happens?
A tick-define is like a text-editor search and replace. These tick-defines
`define ARRAY1 = 3'b001;
`define ARRAY2 = 3'b011;
effectively mean
replace all occurrences of `ARRAY1 with "= 3'b001;"
replace all occurrences of `ARRAY2 with "= 3'b021;"
so
next_state = {`ARRAY1,`ARRAY2};
becomes
next_state = {= 3'b001;,= 3'b021;};
which is nonsense. Basically, remove the semicolons and equals from these lines:
`define ARRAY1 3'b001
`define ARRAY2 3'b011
Related
I am working on a string incrementer project on codewars.
Basicly,
Writing a function which increments a string, to create a new string.
If the string already ends with a number, the number should be incremented by 1.
If the string does not end with a number. the number 1 should be appended to the new string.
If the number has leading zeros the amount of digits should be considered.
foo -> foo1
foo001 ->foo002
foobar23 -> foobar24
foo099 -> foo100
My code is : input.gsub(/\d/,"")+input.split().map {|x| x[/\d+/].next!}.join(" ")
https://repl.it/#tanilserbes/ViolentNoteworthyDowngrade . It works on this playground
However it doesnt work on codewars. I get this error:
main.rb:5:in block in increment_string': undefined methodnext!' for nil:NilClass (NoMethodError)`
Any idea?
thanks in advance!.
To see what's going on here, it's beneficial to run each of your commands individual and see what the output is to track down the error:
input = "foo"
input.gsub(/\d/, "") # => "foo"
So the left hand side of the + operator is going to become "foo" and now we need to see what the right hand side of the is:
input.split # => ["foo"]
["foo"].map { |x| x[/\d+/].next! }
As seen in the question, this is where the error happens, so let's dig into the code inside the map block, where the error is:
["foo"].map { |x| p x }
# Outputs: "foo"
So, x == "foo" at this point:
["foo"].map { |x| p x[/\d+/] }
# Outputs: nil
Since the string "foo" doesn't have any digits in it, the regex pulling out the digits from it, to increment them returns nil and then, without any safeguarding you increment that. NilClass doesn't have a method next!, so you get your error.
If the string was instead "foo1", though, you'd get:
["foo1"].map { |x| p x[/\d+/] }
# Outputs: "1"
Which returns the matched string, and then allows you to call next! (which is a synonym of the String#succ! method called out in the comments) on it. The reason it works in the playground is because the string has digits in it, and doesn't take into account or test the case where strings don't (the first example in the text of the question where "foo" should become "foo1").
Here are some points to consider in developing your solution.
If your string were:
str = "ca9t00456"
the desired return value would be:
"ca9t00457"
(Note that the OP's solution would return an incorrect result ("cat10") for this string. The Codewars question does not say that the only digits in the string are those at the end; it only mentions the "number" at the end of the string".)
A reasonable first step would be to divide the string into two parts:
n = str.index(/\d+\z/)
#=> 4
prefix = str[0, n]
#=> "ca9t"
suffix = str[n..-1]
#=> "00456"
See String#index. The regular expression, /\d+\z/, reads, "match one or more (+) digits (\d) followed by the end of the string (\z). The digit '9' is skipped over because it is neither followed by a digit nor is at the end of the string. See also See String#[].
The string we return will begin with (the value held by) prefix, so we can set that aside for now and concentrate on modifying suffix.
One approach would be:
((suffix.to_i) + 1).to_s
#=> "457"
but then we would have to add the correct number of leading zeroes. Here that would be the same as the number of leading zeroes in suffix (2), but if suffix were, for example, 00999, it would be only one (01000). That could be done, but it's messy.
An easier way would be to use the method String#succ, as #steenslag suggested in the comments.
new_suffix = suffix.succ
#=> "00457"
"00999".succ
#=> "01000"
Now we need only combine prefix and new_suffix.
Note what happens if we execute succ on the entire string:
"ca9t0456".succ
#=> "ca9t0457" correct
"ca9t0999".succ
#=> "ca9t1000" correct
"ca9t9999".succ
#=> "ca9u0000" incorrect
As you see, there's a problem with the third example. That's why I chose to divide the string into two parts as a first step.
You need to investigate three other cases. The first is when the prefix is an empty string:
str = "00456"
the second is when the suffix is an empty string:
str = "ca9t"
and the third is when the string is empty:
str = ""
You can check if the previous calculations still work in the first case.
In the second case we would find:
n = str.index(/\d+\z/)
#=> "cat9t".index(/\d+\z/) => nil
The nil value for n tells us that the desired return value is:
str + "1"
#=> "ca9t" + "1" => "ca9t1"
Would that work?
out_file = File.open "out_file.txt" , 'w' do |f|
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
f.puts "matrix test"
f.puts " int at [0,2]: #{matrix[0][2]}"
f.puts " int at [2,0]: #{matrix[2][0]}"
f.puts " int at {1,1]: #{matrix[1][1]}"
above code produces this:
"matrix test
int at [0,2]: 3
int at [2,0]: 7
int at {1,1]: 5"
but this code using the same matrix variable declaration ..
rows = Array(0..3)
cols = Array(0..3)
rows.each do |r|
cols.each do |c|
f.puts "row:#{r} col:#{c} = #{matrix[r][c]},"
end
end
produces an error:
undefined method `[]' for nil:NilClass (NoMethodError)
Can anybody please tell me what's going on?
The problem is your Array(0..3), it is generating an array [0,1,2,3] instead of what you want: [0,1,2].
You actually want to use ... : Array(0...3) => [0,1,2].
Or you could just change the range inside to 0..2 : Array(0..2) => [0,1,2]
Check out the documentation for Range for more information.
As Tony suggests, using rows=Array(0..2) or rows=Array(0...3) will work for you.
You can also use the range directly and forgo the array creation, like this:
rows = 0...3
cols = 0...3
...
There are 2 types of ranges, the inclusive .. and the exclusive ... which doesn't include the right most digit.
A range such as 0..5 will have every number including the 5. (ie. 0,1,2,3,4,5)
A range such as '0...5' will have every number excluding the 5. (ie. 0,1,2,3,4).
So if you notice your error message,
undefined method `[]' for nil:NilClass (NoMethodError)
You need to begin to wonder what could be running a method on nil. Well, you have this matrix declaration of:
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
So that when this range pops up that is expressed as:
rows = Array(0..3)
It will go through 0,1,2, and also 3. Well, there is no 3 index in that array since your array begins counting at 0 and ends at 2. So when the 3 index hits, the value of it is beyond anything you've declared - it's nil. When you try to run that method on it (to call the spot in the array you want), the error message tells you that you can't run a method (which the [] is actually) on nil.
Paying close attention to your error messages, as well as understanding the 2 types of ranges should help you catch these sorts of errors in the future as well. Leave a comment if this doesn't make total sense.
The previous answers are right, but I thought I would raise the issue of the approach...
Why are you creating ranged arrays instead of using the actual length of the matrix arrays in question...?
Maybe something like this would remove the need to assume the matrix's composition:
out_file = File.open "out_file.txt" , 'w' do |f|
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
f.puts "matrix test"
matrix.length.times do |r|
matrix[r].length.times do |c|
f.puts "row:#{r} col:#{c} = #{matrix[r][c]},"
end
end
val Array(k,s) = readLine.split(" ").map(_.toInt)
This code works fine. But not this:
val Array(k,S) = readLine.split(" ").map(_.toInt)
Capitalizing "s" here gives me an error: error: not found: value S
What is going on?
When you are creating the k and s identifiers with val Array(k,s) = ..., you are using pattern matching to define them.
From the Scala Specifications (1.1 Identifiers):
The rules for pattern matching further distinguish between variable
identifiers, which start with a lower case letter, and constant
identifiers, which do not.
That is, when you say val Array(k,S) = ..., you're actually matching S against a constant. Since you have no S defined, Scala reports error: not found: value S.
Note that Scala will throw a MatchError if the constant is defined but it still cannot find a match :
scala> val S = 3
S: Int = 3
scala> val Array(k, S) = Array(1, 3)
k: Int = 1
scala> val Array(k, S) = Array(1, 4)
scala.MatchError: [I#813ab53 (of class [I)
... 33 elided
When using extractors, symbols that begin with a lower case character will be interpreted as a variable to hold an extracted value. On the other hand, symbols that begin with an upper case character are used to refer to variables/values declared in an outer scope.
Another example:
val X = 2
something match {
case (X, y) => // matches if `something` is a pair whose first member is 2, and assigns the second member to `y`
case (x, y) => // matches if `something` is a pair, and extracts both `x` and `y`
}
I am trying to spawn and evaluate expressions over different processes. The expressions contain local parts of distributed arrays, and this seems to create problems. For example,
addprocs(2)
x = [i for i = 1:10]
foo = #spawnat 2 quote
out = x[1]
for i = 2:5
out += x[i]
end
out
end
eval(fetch(foo))
gives, as expected,
Out [ ]: 15
However, if I try to replace the vector x with a distributed array dx and use only the local chunk in the expression, I get the following error.
# Construct a distributed array dx = [1,2,3,4,5,6,7,8,9,10] #
dx = DArray(I->[i for i in I[1]], (10, ))
dfoo = #spawnat 2 quote
out = localpart(dx)[1]
for i = 2:5
out += localpart(dx)[i]
end
out
end
eval(fetch(dfoo))
Out []: ERROR: BoundsError()
while loading In[9], in expression starting on line 9
in getindex at array.jl:246
in anonymous at In[9]:2
I got the feeling that the problem is the localpart() which is not recognized when the expression is evaluated.
Am I right?
Is there a way around this issue?
Thank you
Here its the quote function that spawns at 2, not the evaluation itself. its like a misusage of spawnat macro.
look at this:
addprocs(2)
foo = #spawnat 2 quote
myid()
end
eval(fetch(foo)) # => 1
And to calculate sum over distributed array: (there is nothing to do with #spawnat)
# Construct a distributed array dx = [1,2,3,4,5,6,7,8,9,10] #
dx = DArray(I->[i for i in I[1]], (10, ))
dfoo = #spawnat 2 quote
sum(localpart(dx))
end
eval(fetch(dfoo))==sum(localpart(dx)) # => true
use warnings;
my #array = (0, 1);
my $scalar1 = $array[0];
my $scalar2 = #array[0];
if($scalar1 == $scalar2) {
print "scalars are equal\n";
}
Here's the output when I run /usr/bin/perl5.10.1 test.pl:
Scalar value #array[0] better written as $array[0] at test.pl line 4.
scalars are equal
I'm concerned about that warning.
You can look up all warning messages in perldoc perldiag, which explains the consequences:
(W syntax) You've used an array slice (indicated by #) to select a
single element of an array. Generally
it's better to ask for a scalar value
(indicated by $). The difference is
that $foo[&bar] always behaves like a
scalar, both when assigning to it and
when evaluating its argument, while
#foo[&bar] behaves like a list when
you assign to it, and provides a list
context to its subscript, which can do
weird things if you're expecting only
one subscript.
On the other hand, if you were actually hoping to treat the array
element as a list, you need to look
into how references work, because Perl
will not magically convert between
scalars and lists for you. See
perlref.
Similarly, you can use diagnostics; to get this verbose explanation of the warning message.
A third way is to use the splain utility.
It is possible to take an array slice of a single element:
#fruits[1]; # array slice of one element
but this usually means that you’ve made a mistake and Perl will warn you that what you really
should be writing is:
$fruits[1];
There are no consequences for that usage. I think the purpose is to help you avoid the consequences when a warning can't be issued.
Slices on the LHS of "=" cause =" to be a list assignment operator.
$ perl -E'sub f { return 4; } my $x = $a[1] = f(); say $x'
4
$ perl -E'sub f { return 4; } my $x = #a[1] = f(); say $x'
1
Slices evaluate the index in list context.
$ perl -E'sub f { my #i = 3; #i } #a=qw( a b c d e f ); say #a[f()]'
d
$ perl -E'sub f { my #i = 3; #i } #a=qw( a b c d e f ); say $a[f()]'
b