Related to my previous question, I have tried to make a function present() for checking the presence of an optional argument. However, the following code
proc present( x ) { return x.type != void; }
proc test( a: ?T = _void )
{
writeln();
writeln( "test| a = ", a );
writeln( "test| condition = ", a.type != void );
writeln( "test| present( a ) = ", present( a ) );
if present( a ) // error (Line 1)
// if a.type != void // works (Line 2)
{
a = 10;
}
}
// no optional arg
test();
// pass an optional array
var arr: [1..5] int;
test( a = arr );
writeln();
writeln( "main| arr = ", arr );
gives a compile-time error
mytest.chpl:3: In function 'test':
mytest.chpl:13: error: illegal lvalue in assignment
mytest.chpl:13: error: a void variable cannot be assigned
which says that the line a = 10; is problematic. On the other hand, if I use Line 2 instead of Line 1, the code works as expected:
test| a =
test| condition = false
test| present( a ) = false
test| a = 0 0 0 0 0
test| condition = true
test| present( a ) = true
main| arr = 10 10 10 10 10
Also, if I replace Line 1 or 2 by if isArray( a ), the code also works. Does this mean that we need to let the compiler explicitly know that the line a = 10; is not reached when a is _void? (In other words, is present() not sufficient to let the compiler know it because the test condition is "hidden" inside present()?)
Does this mean that we need to let the compiler explicitly know that
the line a = 10; is not reached when a is _void? (In other words, is
present() not sufficient to let the compiler know it because the test
condition is "hidden" inside present()?)
Yes, that's right. The compiler needs to know at compile-time that the body of that if should be compiled only in the case that the argument not void. Putting the x.type != void check in that conditional is a reasonable solution but if you want to have a function to compute if that conditional should be evaluated, you can do so. Just mark present as a param function - which means that it returns a value that should be known at compile-time. Here is the complete example:
proc present( x ) param { return x.type != void; }
proc test( a: ?T = _void )
{
writeln();
writeln( "test| a = ", a );
writeln( "test| condition = ", a.type != void );
writeln( "test| present( a ) = ", present( a ) );
if present( a )
{
a = 10;
}
}
// no optional arg
test();
// pass an optional array
var arr: [1..5] int;
test( a = arr );
writeln();
writeln( "main| arr = ", arr );
If you would like to read more about the language design in this area, see "The Param Return Intent" subsection in "Procedures" chapter section "Return Intents" of the language specification.
Related
So I know I'm missing something obvious, however, after searching similar/related questions, I can't quite figure out what I'm doing wrong.
New to Kotlin, so probably something I'm not understanding properly.
Creating an ArrayList, as I need a growing list of items, starting with none. Think of it like an undo list. It'll grow to an unknown size. At some point, I'll reset it back to "empty" when needed.
Inside this list, I need an Array of Integers. These 3 values are a co-ordinate system - if it matters (ie x,y,z).
Everything I try, I keep ending up only being able to retrieve the final IntArray set added.
Using:
https://developer.android.com/training/kotlinplayground
fun main() {
// array list
var myList = arrayListOf<IntArray>()
// 3 item "test" array to populate array list with
var myArr = IntArray(3){0}
// setup Array list with 3 items
for ( b in 0..2 ) {
// fake/create a temp array with some simple values
for ( i in 0..2 ) { myArr[i] = 3+b+(3*i) }
// add it to the List
myList.add(b, myArr)
// confirm values
println ( "Added [" + myList.lastIndex +"] = " + myArr[0] +"-"+ myArr[1] +"-"+ myArr[2] )
}
// confirm size of Array List
println ( "size: " + myList.size )
// test pull the middle array from the ArrayList
// indices should be: 0, 1 and 2
var testArr = myList.get(1)
println ( "for idx 1: vals: " + testArr[0] +"-"+ testArr[1] +"-"+ testArr[2])
// test display all values for all arrays
myList.forEach {
println ( "Vals: " + it[0] +"-"+ it[1] +"-"+ it[2] )
}
// another method to do same ?
for ((index,value) in myList.withIndex()) {
println("index: $index ... " + value[0] +"-"+ value[1] +"-"+ value[2])
}
}
output is:
Added [0] = 3-6-9
Added [1] = 4-7-10
Added [2] = 5-8-11
size: 3
for idx 1: vals: 5-8-11
Vals: 5-8-11
Vals: 5-8-11
Vals: 5-8-11
index: 0 ... 5-8-11
index: 1 ... 5-8-11
index: 2 ... 5-8-11
Everything makes perfect sense up until the repeats of "5-8-11" .. what am I doing wrong?
I read your code, I think the problem is the IntArray you use, it is an object, every time you add it to the list, it is the same object. so In the end, it is always the same element.
please change the code to the following:
...
for ( b in 0..2 ) {
// fake/create a temp array with some simple values
var myArr = IntArray(3){0}
for ( i in 0..2 ) { myArr[i] = 3+b+(3*i) }
// add it to the List
myList.add(b, myArr)
// confirm values
println ( "Added [" + myList.lastIndex +"] = " + myArr[0] +"-"+ myArr[1] +"-"+ myArr[2] )
}
...
that should resolve your problem.
Here is the explanation of the reference object
As you work with objects, it's important to understand references.
A reference is an address that indicates where an object's variables and methods are stored.
You aren't using objects when you assign an object to a variable or pass an object to a method as an argument. You aren't even using copies of the objects. Instead, you're using references to those objects.
Here is the description about kotlin, it explains by image and content, you can read this.
The issue is that in:
for ( i in 0..2 ) { myArr[i] = 3+b+(3*i) }
you always modifying and adding the same object: myArr .
To fix, replace
for ( i in 0..2 ) { myArr[i] = 3+b+(3*i) }
with
val a = IntArray(3) { i -> 3+b+(3*i) }
and then add a:
myList.add(a)
Or, if populating the IntArray is as simple as in the example just:
myList.add(IntArray(3) { i -> 3+b+(3*i) })
The final code looks like this:
fun main() {
val myList = arrayListOf<IntArray>()
// setup Array list with 3 items
for ( b in 0..2 ) {
myList.add(IntArray(3) { i -> 3+b+(3*i) })
}
for ((index,value) in myList.withIndex()) {
println("index: $index ... " + value[0] +"-"+ value[1] +"-"+ value[2])
}
}
or even more concise (probably too much):
fun main() {
val myList = List(3) { b -> IntArray(3) { i -> 3 + b + (3 * i) } }
for ((index, value) in myList.withIndex()) {
println("index: $index ... " + value[0] + "-" + value[1] + "-" + value[2])
}
}
Creating an ArrayList, as I need a growing list of items, starting
with none. Think of it like an undo list. It'll grow to an unknown
size. At some point, I'll reset it back to "empty" when needed.
This sounds like you need a Stack. You could use a MutableList for this, or the ArrayDeque class. With size, addLast(element), clear, contains(element), isEmpty(), last() , and removeLast() you have everything at hand for manipulating something like an Undo list.
To construct it you would do:
val stack = ArrayDeque<IntArray>()
for (b in 0..2) {
val intArray = IntArray(3)
for (i in 0..2) {
intArray[i] = 3 + b + (3 * i)
}
stack.addLast(intArray)
}
stack.forEach { println(it.joinToString("-")) }
Output:
3-6-9
4-7-10
5-8-11
I want to create an if code to check if variable x is a member of a defined group of constant named a, for example a = { 1 , 2 , 3 , 4 }, then use something like if (x != a).
I only know to use it like this
if ( ( x != 1 ) || ( x != 2 ) || ( x != 3 ) || ( x != 4 ) )
You can use functions like this
bool exist_in_group(int value, const int* group,int group_size)
{
bool res{false};
for(int i=0;i<group_size;i++)
{
if(group[i] == value)
res = true;
}
return res;
}
This function check if value exist in your array(group) or not
Given some mock function which takes at least one parameter:
MOCK_METHOD1(fun, void(int p));
How can i EXPECT_CALL two identical calls in terms of the value of parameter p? I don't care what the value of p actually is, as long as it is the same for both calls to the function fun. I have no way to predict the value of p in the test case.
Option #1
EXPECT_CALL( mock, fun( testing::Truly( []( int p ) {
static int initial = p;
return initial == p;
} ) ) )
.Times( 2 );
Option #2
int p = 0;
testing::Sequence seq;
EXPECT_CALL( mock, fun( _ ) )
.InSequence( seq )
.WillOnce( testing::SaveArg< 0 >( &p ) );
EXPECT_CALL( mock, fun( testing::Eq( testing::ByRef( p ) ) ) )
.Times( 1 )
.InSequence( seq );
I have a string with multiple / in it and I am trying to convert this string in to LaTeX code. Basically (a)/(b) becomes \\dfrac{a}{b}.
The difficulty is that (a) and/or (b) could contain other /.
To respect the parentheses balancing, I would like to replace the / from left to right, and replacing them accordingly to what it around. I made a try but I don't know how target a specific / and replace. using position and length parameters seems to be very complicated.
function ToFrac (s)
while s:find ("/") ~= nil
do
-- Replace : \dfrac{}{}/() -> \dfrac{\dfrac...}{}
if ( s:find ( '\\dfrac%b{}%b{}/%b()' , j ) ~= nil )
then
x,y,num,den = s:find( '(\\dfrac%b{}%b{})/(%b())' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(\\dfrac%b{}%b{})/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end
print ('### -- ', s)
-- Replace : ()/\dfrac{}{} -> \dfrac[}]{\dfrac...}
if ( s:find ( '(%b()/\\dfrac%b{}%b{}' ) ~= nil )
then
x,y,num,den = s:find( '((%b())/(\\dfrac%b{}%b{})' )
num = num:gsub( '.(.+).' , '%1' )
s = s:gsub( '((%b())/()\\dfrac%b{}%b{})',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end
print ('### -- ', s)
-- Replace : ()/() -> \dfrac{}{}
if ( s:find ( '%b()/%b()' , 1 ) ~= nil )
then
x,y,num,den = s:find( '(%b())/(%b())' )
num = num:gsub( '.(.+).' , '%1' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(%b())/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
Done = true
end
print ('### -- ', s)
end -- while
return (s)
end
s = "((a)/(b))/(c)"
print (s, ToFrac(s))
s = "(a)/((b)/(c))"
print (s, ToFrac(s))
s = "(a)/(b)/(c)/(d))"
print (s, ToFrac(s))
s = "((a)/(b))/((c)/(d))"
print (s, ToFrac(s))
Amended version of rpattiso's idea:
function to_frac(expr)
local t
return expr == '' and '' or (expr..'()'):gsub('(.-)(%b())',
function(prefix, subexpr)
local replace_with = ''
if not prefix:find'^%s*/%s*$' then
t, replace_with = {}, (not t and ''
or t[2] and '\\dfrac{'..t[1]..'}{'..t[2]..'}'
or '('..t[1]..')')..prefix
elseif t[2] then
t = {'\\dfrac{'..t[1]..'}{'..t[2]..'}'}
end
table.insert(t, to_frac(subexpr:sub(2,-2)))
return replace_with
end
)
end
print(to_frac' (a )/((b) / (c))') --> \dfrac{a }{\dfrac{b}{c}}
print(to_frac'((a)/((b)/(c)))/(e)') --> \dfrac{\dfrac{a}{\dfrac{b}{c}}}{e}
print(to_frac'(a)/(b)/(c)/(d)') --> \dfrac{\dfrac{\dfrac{a}{b}}{c}}{d}
The 'replace' argument of string.gsub can be a function.
Using that function, you can apply the substitution recursively to the numerator and denominator and build the result that way. string.sub can be used to remove the parentheses from the numerator and denominator.
function to_frac(expr)
return (expr:gsub('%s*(%b())%s*/%s*(%b())%s*',
function(num, denom)
return '\\dfrac{'..to_frac(num:sub(2,-2))..'}{'
..to_frac(denom:sub(2,-2))..'}'
end))
end
expr = ' (a )/((b) / (c))' -- \dfrac{a }{\dfrac{b}{c}}
print(to_frac(expr))
expr = '((a)/((b)/(c)))/(e)' -->\dfrac{\dfrac{a}{\dfrac{b}{c}}}{e}
print(to_frac(expr))
If you want to go beyond using parentheses for delimiting arguments and obey precedence rules, then look into LPeg.
i have some enum class
enum class Foo { A=1, B=18 , Z=42 };
i want to check if some integer can be converted into a Foo.
What would be the ideal way to do this? this is for runtime check (the integer is not known yet at compile-time)
Obviously i can do this the hard way (write a function bool CheckEnum(Foo); with a big-ass switch returning true for all cases except the default one), but i was hoping a more elegant mechanism that avoided so much writing. MPL or Boost.Preprocessor would be a perfectly acceptable solution, but one of which i sadly know very little about
A solution to this problem is to ditch the enums, and replace it with some arrays which are created using XMACROs.
There is no "ideal" way to do it. All ways are going to have to involve some manual work.
You need to create a data structure that contains all of the acceptable values. Then search that data structure with the runtime value you need. A std::set or std::unordered_set would be adequate for this purpose.
Your main difficulty will be in maintaining that list, as it will need to be updated every time you change your enum class.
Ok i'm a little bit fed up with this issue (some of my enums are nearly 100 items)
so i decided to tackle it with code generation, which might not be everyone's cup of tea, but i've realised that is really no such a big deal.
Basically i went for Python Cog, which allows me to embed python snippets inside comments in my .h and .cpp files and auto-generate code. I use it basically like a really smart, imperative macro system:
i added the following to Test.h
/*[[[cog
#----------- definitions
import cog
def createCategoryConstants( enumVar , bitShift ):
categoryIndex = 0
for cat in enumVar:
cog.outl(' const unsigned int %s_op_mask = (%d << %d); ' %(cat[0] , categoryIndex , bitShift))
categoryIndex += 1
cog.outl('\n\n')
def createMultiCategoryEnum( enumVar , enumTypename ):
cog.outl(' enum class %s { ' % enumTypename )
categoryIndex = 0
for i in enumVar:
itemIndex = 0
catName = 'NotExpected'
remainingCategories = len(enumVar)- categoryIndex - 1
for j in i:
if (itemIndex == 0):
catName = j
itemIndex = 1
continue
enumItemIndex = 0
for enumItem in j:
remainingEnums = len(j) - enumItemIndex - 1
currentLine = ' %s = %s_op_mask | %d ' %(enumItem, catName, enumItemIndex)
if (remainingCategories != 0 or remainingEnums != 0):
currentLine += ' , '
cog.outl(currentLine)
enumItemIndex += 1
itemIndex += 1
cog.outl('') #empty line to separate categories
categoryIndex += 1
cog.outl(' };\n\n')
def createIndexFromEnumFunction( enumVar , enumTypename , functionName ):
cog.outl('uint32_t %s(%s a) { \n switch (a)\n {' % (functionName , enumTypename) )
absoluteIndex = 0
for cat in enumVar:
elemInCat = 0
for i in cat:
if elemInCat != 0:
for enumItem in i:
cog.outl('case %s:' % enumItem)
cog.outl(' return %d; \n' % absoluteIndex)
absoluteIndex += 1
elemInCat += 1
cog.outl(' } \n } \n\n ')
def createMultiEnum( enumVar , enumTypename ):
createCategoryConstants( enumVar , 4)
createMultiCategoryEnum( enumVar , enumTypename )
createIndexFromEnumFunction( enumVar , enumTypename , 'FromOpToIndex' )
#------------- generation
multiEnum =[ ['CatA', ['A1', 'A2' , 'A3_foo']] , ['CatSuper8' , ['Z1_bla' , 'Z10' , 'Z11']] ]
createMultiEnum( multiEnum , 'multiFooEnum')
]]]*/
//[[[end]]]
Then i added cog invocation in my Makefile pre-build step:
.build-pre:
# Add your pre 'build' code here...
python /usr/local/bin/cog.py -I../../../tools/cog/ -r *.h
And the results show up just below:
]]]*/
const unsigned int CatA_op_mask = (0 << 4);
const unsigned int CatSuper8_op_mask = (1 << 4);
enum class multiFooEnum {
A1 = CatA_op_mask | 0 ,
A2 = CatA_op_mask | 1 ,
A3_foo = CatA_op_mask | 2 ,
Z1_bla = CatSuper8_op_mask | 0 ,
Z10 = CatSuper8_op_mask | 1 ,
Z11 = CatSuper8_op_mask | 2
};
uint32_t FromOpToIndex(multiFooEnum a) {
switch (a)
{
case A1:
return 0;
case A2:
return 1;
case A3_foo:
return 2;
case Z1_bla:
return 3;
case Z10:
return 4;
case Z11:
return 5;
}
}
//[[[end]]]
So, now my enum validation is about making sure the code generation (invoked at compile time) is done correctly