sepp2k 378 Practically a Master Poster

You could compile all three and use objdump to disassemble the machine code generated to identify which is fastest

That doesn't tell you which is fastest, it only tells you which compiles to which instructions. It might be easier to predict the runtime when looking at assembly code than when looking at C code, but there's still a lot of variables.

First of all you'd need to know how fast each instruction is on the given architecture. In more complicated cases you'd also need to know how the code behaves with regards to caching, branch prediction and/or pipelining. Predicting those things just by looking at the assembly is not very reliable.

So the most reliable way to find out how fast a given piece of code is, is to measure. Looking at the assembly may give you a better idea of why a given piece of code is faster, but reading the assembly should not be a substitute for measuring.

PS: Most compilers have a way of outputting assembly code direclty (-S in gcc), so you won't need objdump.

sepp2k 378 Practically a Master Poster
3(1-x3)

This is interpreted as "call the function 3 with the argument 1-x3" and since 3 isn't a function, you get that error message. I assume you simply forgot a * there.

sepp2k 378 Practically a Master Poster

If you enter 0 0 0 as the input of your code, the loop terminates. So as I said, the function will return true for that input.

sepp2k 378 Practically a Master Poster

You're wrong, as I said, it does not always return false. Proof: http://codepad.org/JQLTsYWA

sepp2k 378 Practically a Master Poster

You're returning false if the month is between 1 and 12 or the day is between 1 and 31 or the year 1753 or later. So if you want to get true, you have to give a day that's less than 1 or greater than 31 (and if it is greater than 31, it also needs to be a leap year), a month that's less than 1 (if it's greater than 12, line 7 will take effect) and a year that's less than 1753.

sepp2k 378 Practically a Master Poster

When ever a multiplication code is called the compiler will perform inner addition operation.

What? It might have been common for CPUs to not support multiplication over 30 years ago, but I doubt very much that any such CPUs exist now. So there's no reason for a compiler to implement multiplication in terms of addition¹.

And even if there were some low-end embedded CPU still in use somewhere that did not support multiplication, there's no way that a modern compiler wouldn't find a way to compile to something more efficient than repeated addition when multiplying by a constant.

As a general rule: whenever you think you can low-level optimize something better than the compiler can, you're probably wrong.

¹ Except in cases where that might actually be faster like replacing x*2 with x+x - except that would actually be compiled to x << 1 probably.

sepp2k 378 Practically a Master Poster

Because '(foo bar baz) is the same as (list 'foo 'bar 'baz) and since numeric constants are self-evaluating, '2 and '3 are just equal to 2 and 3, so the whole thing comes out as (list 2 '+ 3) (i.e. a list containing the number 2, the symbol + and the number 3).

So if that's your input, you'll need one of those options that I mentioned - or just a boring list of conditions like (equal? op '+), (equal? op '-) etc.

sepp2k 378 Practically a Master Poster

Ideally you'd make it so that the list contains + instead of '+ in the first place. If that's not possible (because you have no control over the lists), you could either use eval or a map or associative list that maps the symbols to their corresponding functions depending on your exact needs.

sepp2k 378 Practically a Master Poster

You can call a function that gets each piece, but your getOperator function needs to return +, not '+. For example this would work:

(define (get-operator expression)
  (cond
    ((some condition) +)
    ((other condition) *)
    (...)))

But this will not:

(define (get-operator expression)
  (cond
    ((some condition) '+)
    ((other condition) '*)
    (...)))

PS: The naming convention in Scheme (and Lisps in general) is to separate words in a name by -, not camel case. So getOperator would more idiomatically written as get-operator.

sepp2k 378 Practically a Master Poster

I think there's been an important confusion of terminology here, so I just want to clear this up:

The three paragraphs you quote above ALL refer to floating constants, and clearly state that, right at the start of each paragraph.

Yes, because, as I said, what you call "magic numbers" is called a constant. The standard defines a floating constant as a sequence of digits with a dot in between (or an E or whatever). Unless I completely missed your point, that's what you refer to when you use the term "magic number": a sequence of digits. The term "magic number" does not exist in the standard.

handling "magic numbers" as constants

They aren't "handled" as constants, they are what standard defines to be a constant. The terms (integer + floating) "constant", as defined by the standard, and "magic number", as used by you, are 100% equivalent (again: unless I completely misinterpreted what you're trying to say). There's nothing that you would call a magic number that doesn't meet the standard's definition of a constant and there's nothing that would meet the standard's definition of a floating or integer constant that you would not call a constant.

deceptikon commented: Beat me to it. :) +12
sepp2k 378 Practically a Master Poster

What you call magic numbers, is called a constant. And the section I quoted tells you exactly how constants are handled.

Note that the standard specifically says that a sequence of digits containing a . or an e, E, p or P is a floating constant. It does not say anything about the sequence having to appear in a specific context to be a constant. If it's a sequence of digits with a . in between, it's a floating constant. And if it does not have a suffix, its type is double.

sepp2k 378 Practically a Master Poster

Okay, that's just not true. Here's the relevant excerpts from the 99 standard (section 6.4.4.2 "Floating Constants"):

Description:

A floating constant has a significand part that may be followed by an exponent part and a suffix that specifies its type. The components of the significand part may include a digit sequence representing the whole-number part, followed by a period (.), followed by a digit sequence representing the fraction part. The components of the exponent part are an e, E, p, or P followed by an exponent consisting of an optionally signed digit sequence. Either the whole-number part or the fraction part has to be present; for decimal floating constants, either the period or the exponent part has to be present.

Semantics:

[...] For decimal floating constants [...] the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner.[...]

An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float. If suffixed by the letter l or L, it has type long double.

As you see in the description a floating constant would be something like 5.2 (whereas a would be a variable - not a constant). And as the bolded part in the semantics indicates, the type of a floating literal without a suffix is indeed double.

sepp2k 378 Practically a Master Poster

Of course it's a constant (or literal if you prefer that term - though the standard uses the term constant). I may not be an absolute expert on every quirk of the C standard, but I know that much for sure.

If 5.2 is not a double, does that mean that 5.2f is not a float? If so what is the difference between 5.2 and 5.2f?

sepp2k 378 Practically a Master Poster

In most cases it is unreasonable to use an operator==(...) for a floating-point values equality check.

Nobody argued against that. I get that and why 0.1 + 0.2 will not equal 0.3 and that it is dangerous to use == to compare floating point values because it can give results like this when doing arithmetic (or conversions between floating point types of different width).

I just said that in this specific case, where there was no arithmetic and no conversions, I see no reason why a conformant implementation would return false for ==.

sepp2k 378 Practically a Master Poster

My understanding is the following: expressions have types. A variable is one kind of expressions - constants are another. Integral constants default to type int and floating point constants default to type double. A constant can be given a different type using a suffix (like l to make an integral constant type long or f to make a floating point constant type float). Is this not correct?

sepp2k 378 Practically a Master Poster

5.2 is an absolute value - it is NOT the same as the double a which was assigned the value of 5.2 AS A DOUBLE.

Isn't 5.2 simply a constant of type double?

sepp2k 378 Practically a Master Poster

I understand floating point. I'm saying if 5.2 is represented as 1.m * 2**e, which happens to be 5.2000001, then 5.2 == 5.2000001 should still be true because it'd just be 1.m * 2**e == 1.m * 2**e.

sepp2k 378 Practically a Master Poster

The value 5.2 might actually be stored in memory as 5.200001

You make it sound like it's non-determinstic. If 5.2 and 5.200001 are the same number under the given floating point representation, x == 5.2 and x == 5.200001 should simply both return true if x has been set to 5.2. Generally in a conforming implementation foo = constant; foo == the_same_constant; should only ever produce false if foo and the constant have different types (and thus the assignment causes a conversion) - unless I'm missing something. Floating point inaccuracies should only bite you if you're doing arithmetic.

sepp2k 378 Practically a Master Poster

The first is undefined behavior because there is no sequence point between function arguments.

The second might be due to differences in precision when the value is only held in a register versus when it is stored in memory. That's my best guess anyway (though I don't think it's conforming behavior).

sepp2k 378 Practically a Master Poster

It's not quite clear to me, what you're trying to do here. If you want the division to only happen if x = 1 is false, it should be inside the else block of the first if. Also every if needs an else, so your first if causes a syntax error because it doesn't.

Also if x is supposed to be the result of the division, why do you already use it on line 2 when the division hasn't happened yet? Further to define a local variable, you'd use let, just writing x = value is not syntactically valid. If you want to change the value of an already existing int variable named x, you can't do that. Variables in SML are immutable. If you want to simulate mutable variables, you can use an int ref instead. But you probably shouldn't.

It also seems strange that your hello function does not take any arguments. Or that both operands to the division are constant (why not just write x = 2 then?).

Here's something that I think might be close to what you might want:

fun hello x =
    if x = 1 then true
    else
        let
            val y = 10 div x
        in
            if x = 4 then true
            else false
        end;
sepp2k 378 Practically a Master Poster

I'm sorry, I do not understand your reply. I said that "in that case it [i.e. sizeof(*p)] would return sizeof(int) * 200". So yes, that's the same as sizeof(*p) (if p had been defined as a pointer to an array) - that's what I was saying.

sepp2k 378 Practically a Master Poster

You are creating a pointer to an array

No, he's not. He's creating an array of arrays of pointers.

and trying to output the size, this is not allowed sice the compiler does not know what the pointer is pointing to.

Yes, it's allowed and yes, the compiler knows perfectly well what p (or rather the pointer that p decays to) is pointing to: to a 20 element arrays of int pointers. So it returns sizeof(int*) * 20

And if he had created a pointer to an array (by writing int (*p)[10][20] instead of int *p[10][20]), it'd still be allowed and the compiler would still know what p points to: a 10x20 array of int. So in that case it would return sizeof(int) * 200.

ddanbe commented: Nice! +14
sepp2k 378 Practically a Master Poster

factorial(10) is just an unidiomatic way to write factorial 10, i.e. it calls factorial with the number 10 as its argument. The reason that it works is that it's legal to surround any expression with parentheses. For the same reason it would also be legal to write val x = (10) instead of val x = 10 or (10) + (4) instead of 10 + 4.

When you write find (3, [1,2,5]), you're calling find with the tuple (3, [1,2,5]) as its argument. Since the argument to find can be of any type, SML accepts this and simply remembers that ''a (the type of the argument to find) is int * int list, i.e. a tuple containing an integer and a list of integers. Since the return type of find is ''a list -> bool and ''a in this case is int * int list, that means that this call to find will return a function of type (int * int list) list -> bool as its result, which clearly isn't what you want.

As I said, you need to decide when you define a function (that needs more than one argument) whether you want it to take its arguemnts in form a tuple of arguments or whether you want it to be curried and then you need to call it that way.

sepp2k 378 Practically a Master Poster

You're defining your function as f x y, so it's a curried function of type ''a -> ''a list -> bool. However you call it recursively as f (x, tl y), so you call it with a tuple as its argument.

If we insert a tuple ''b * ''b list as ''a into the type signature, we get (''b * ''b list) -> (''b * ''b list) list -> bool, so the expression find (x, tl y) has the type (''b * ''b list) list -> bool. However it should just have the type bool. Therefore you get a type error.

To fix your issue you should either call your function as a curried function (find x (tl y)) or define it as a tupled function fun find (x,y) = .... You can't define it as one and call it as the other.

sepp2k 378 Practically a Master Poster

Can you be more specific about what kinds of problems you're looking for in terms of scope and "topic" (like should they be more about algorithms or application design etc.) and how tough they should be?

If you're interested in algorithmic problems, you can find ones of various difficulties on sites like the Spehere Online Judge or the UVA Online Judge. If you're interested in mathematical problems (with programatic solutions), Project Euler has many nice ones (though most of them are pretty tough and generally require more mathematical than programming knowledge).

sepp2k 378 Practically a Master Poster

I wonder if the OP's compiler is assuming a one-parameter prototype

When a function is implicitly declared in C, the inferred prototype will have the same number of arguments as the function call (and all of the arguments' types will be int).

Also the arity of a function is not information that's relevant to the parser, so calling a function with the wrong number of arguments can't cause a parse error. It would produce a "wrong number of arguments" error at a later stage of the compilation.

Whether a given identifier refers to a type on the other hand is relevant to the parser, so that can cause a parse error.

sepp2k 378 Practically a Master Poster

Which compiles just fine in Visual Studio

TIL: Visual Studio's <string> header includes <cstring> (or at least somehow declares strcpy). But yes, that's pretty much what I tried in gcc.

However, it could very easily be this

Interesting, that does indeed cause an error. In fact it produces the exact error message the OP complained about. So that's almost definitely it.

So I assume the rule is if there's a type and a variable with the same name, the compiler picks the one with the closer scope (i.e. it will prefer local names over global ones and, presumably, names local to, say, a loop over names local to the whole function) and if the scope is the same, it will always interpret it as a type name? I did not know that. Thank you.

sepp2k 378 Practically a Master Poster

I suspect the OP is compiling it as C++ where string is very likely to cause issues due to potentially being exposed as a type name.

Why would it be likely to cause issues in C++? g++ doesn't complain about the OP's code, even if I add #include <string> and using std::string.

A more complete example would help in diagnosing this error.

Definitely.

sepp2k 378 Practically a Master Poster

It will be whichever the compiler chooses (arbitrarily or not). So, clearly, there is no telling which of the increment operators will be evaluated first. And thus, it is "undefined behavior".

You seem to be implying that the behavior will definitely be that of one of the possible orderings, but that's not the case. It's just not unspecified, which increment happens first - the behavior is completely undefined. As far as the standard is concerned, the code may print "23 42" or even crash.

In fact gcc produces "4 5" as the output, which is neither consistent with a++ being evaluated first (that should produce "3 5"), nor with ++a evaluated first (that should produce "4 4").

So, for the most part, sequence points coincide with where you'd find semi-colons (;) in the code (with the exception of short-circuit operators like && and ||).

The comma operator and the conditional operator introduce sequence points as well. As do function calls (that is there is a sequence point between the evaluation of the arguments and the evaluation of the body - there is no sequence point between the function's arguments).

Speaking of function calls, I need to correct my earlier answer: The fact that the built-in << operator does not introduce a sequence point is irrelevant because here we're using an overloaded << operator and overloaded operators behave like function calls. This doesn't change that the behavior is undefined though since there is no sequence point between …

vijayan121 commented: Yes +14
sepp2k 378 Practically a Master Poster

Yes.

sepp2k 378 Practically a Master Poster

Yes, it's undefined behavior. << does not introduce a sequence point, so you are indeed modifying a twice without a sequence point in between.

sepp2k 378 Practically a Master Poster

As the error message says, input only expects a single argument (or none), but you give it three. The print function can take multiple arguments and will then just print one after the other (on the same line). The input function does not do that - you have to call it with a single string.

To create a single string for your prompt, you can use the format method like this:

action = input("Trade number {} (buy/sell)?".format(i))
Gribouillis commented: indeed +14
sepp2k 378 Practically a Master Poster

I'm not sure what you mean. If you want to put your member functions into your vector, you need to change the type of your vector (and then also change the calls when you call the functions). An example of this would be:

class CPerson
{
        public:
                CPerson(void) {};
                ~CPerson(void) {};
                typedef std::function<bool(CAle&, CPerson*, CPerson*)> FUNCTIONPOINTER;
                vector<FUNCTIONPOINTER> fp_Sip;
};

int main(void)
{
        // ...
        for (auto it = Person.fp_Sip.begin(); it != Person.fp_Sip.end(); ++it)
                (*it)(Ale, pP1, pP2);
        Person.fp_Sip.at(enSip3)(Ale, pP1, pP2);
}

If you don't want that, you need to bind the first argument using std::bind.

PS: Note that there's a lot of undefined behavior in your program as your bool functions don't actually return a value and you don't initialize your pointers.

PPS: The return value of main should be 0 - not 1 - when your application exits successfully.

sepp2k 378 Practically a Master Poster

Are you sure you don't get any errors on the lines where you call push_back? Because that's where I would expect errors to happen.

Anyway the problem I see is that your functions are member functions of CAle and thus need to be called on an object of type CAle. By wrapping them with mem_fn you're creating a function object that takes three arguments: an object of type CAle on which to call the function and two CPerson pointers to pass as arguments. However your vector is supposed to store functions/function objects that take two arguments, not three, and the first argument is supposed to be of type CPersion*, not CAle.

sepp2k 378 Practically a Master Poster

Currently you have a regex that matches the whole string and then replace that with 'a'. So the whole string is going to be replaced with a single 'a'.

If all you want is to replace every character with one 'a' per character, just use a regex that matches a single character. If there are no special requirements on the characters, you can just do:

result = re.sub('.', 'a', 'Cat')

The count = 0 is unnecessary because that's the default.

sepp2k 378 Practically a Master Poster

Here's my solution in Brainf#ck:

https://gist.github.com/anonymous/6422016

Sample run:

Please enter your favorite food:
apple
Please enter your second favorite food:
banana
This will be your new favorite food:
applebanana

This was fun.

Edit: Moved the code to a gist because I realized it's way too long to post here.

sepp2k 378 Practically a Master Poster

But execfile('func.py') produced no such error?

If both files are in the same directory, I don't know why it wouldn't work. If they aren't exefile shouldn't have worked either. So my only idea is that you maybe accidentally somehow moved the files into different directories when you replaced execfile with import - or you created a new file to test import and that file is in a different directory than func.py.

sepp2k 378 Practically a Master Poster

Yes, according to ANSI C, you need to specify the return and argument types when defining or declaring a function. Not doing so is an error.

You need the return statement because the return statement is used to return values from a function. If you use the return value of a function, but that function did not return a value using a return statement, the behavior is undefined (even in pre-ANSI C).

It might seem to you that using a macro (which doesn't require any types or return statements) might be easier because of this, but as we just saw, using macros means that you have to be very careful with parentheses if you want to get correct results. So not using macros will save you a lot of pain and is definitely worth it.

sepp2k 378 Practically a Master Poster

In Python a variable is defined when you first assign something to it. In your code you never assign anything to y, so it is not defined. You can not use variables that are not defined. As you already figured out, assigning something to y before the loop defines y and thus fixes that error.

Your other problem is that you assign y to be an empty list. For any list y, writing y[i] (whether it's to read from that position or write to it) is only legal if i is a valid index for the list. A valid index for a list of size n is either a non-negative integer less than n or a negative integer greater than or equal to -n. So since your list has a size of 0, there are no valid indices for it (a number can't be less than 0 and non-negative at the same time nor can a negative number be greater than or equal to 0). In other words: it's never legal to write y[i] if y is an empty list.

To add elements to a list you use the append method like y.append(x[-(i+1)]. This adds the given element to the end of the list, increasing its size by one.

Edit: God, I type slowly.

sepp2k 378 Practically a Master Poster

It's just import func - import func(func) isn't legal syntax in Python. Other than that: yes, like that.

sepp2k 378 Practically a Master Poster

The return value of execfile is always None. All it does is to execute the code in the file. It does not check whether the last statement in the file is an expression and if so return its value or anything like that.

If you want to use func's return value, you should remove the call to func from func.py, import func (or from func import func in your calling code and then call func.func(z) (or just func(z) if you used from) in that file.

Since your func.py can't stand on its own anyway (z wouldn't be defined if you tried to run it directly), I assume that removing the call won't be a problem.

sepp2k 378 Practically a Master Poster

You mean about adding parentheses or using a function? For the former I meant that it should be #define func(x,y) (3 * (x) * (y)) or you'll get wrong results because of precedence in the expanded code.

For the latter I meant that you should just use int func(int x, int y) { return 3 * x * y; } and avoid any such issues.

sepp2k 378 Practically a Master Poster

You can also use for animal, noise in instead of for tpl in. Then you can use animal and noise instead of tpl[0] and tpl[1] respectively.

M.S. commented: thanks :) +4
sepp2k 378 Practically a Master Poster

It's valid, but it very likely won't do what the OP wants it to. You'll need parentheses around the arguments and the whole expression (though the latter doesn't matter in this case).

Or they could make their life 1000 times easier and define it as a function instead of a macro.

sepp2k 378 Practically a Master Poster

I'm guessing you're using Python 3.x where print() takes exactly one argument.

That's not true. In Python 3 print takes arbitrarily many arguments. Further the OP's code won't work in Python 2 either.

The syntax to call print (or any other function) with multiple arguments in Python 3 is print(arg1, arg2, etc). In Python 2 it's print arg1, arg2, etc. So the difference is the lack of parentheses. In either case print (arg1)(arg2)(etc) is wrong.

In Python 2 it is interpreted as calling arg1 with arg2 as its argument and then calling the result of that with etc as its argument and then printing the result. Of course that only works if arg1 is a function (or other callable object) and arg1(arg2) also returns a function (or other ...).

In Python 3 it is interpreted as calling print with arg1 as the argument, then calling the result of that with arg2 as the argument and then calling the result of that with etc as the argument. Since the result of print(arg1) is None (no matter what arg1 is), this will lead to the error message that the OP is getting.

sepp2k 378 Practically a Master Poster

The stringstream class has no copy assignment operator (and no copy constructor, but that's less relevant). Thus you can't write things like entries[key] = SS; or SS = i->second;.

You can make your code work by directly working with the objects in the map and avoiding any copies.

sepp2k 378 Practically a Master Poster

The construct template<typename T> is used to paramatrize classes, structs, unions, functions or, in C++ 11, type aliases with type parameters (or in some cases other compile-time parameters). So template<typename T> must be in front of the definitions of one of those things (like template<typename T> class Foo {...}). In your case it's inside a function body, which is not allowed.

It's not clear what you want parametrize here. If you wanted to parametrize main, you'd need to write template<typename T> int main(), except that it's not legal for main to be a template function because main is called by the operating system and the OS would not know which type to supply as an argument.

So you'd need to define your own function template<typename T> mymain(), put the code in there and then call that from main with the appropriate type argument. Except that won't work either because:

T one = "test";
T two = 255;
T three = 287.52;
T four = 'x';

Those four variables can't have the same type (unless there's a custom defined class with implicit constructors accepting each of the four types, but in your code there's not).

It's important to understand that in any given instantiation of a template, all occurrences of T refer to the same type. So if call, say mymain<int>() and mymain contains the above code, it will behave like you wrote:

int one = "test";
int two = 255;
int three = 287.52;
int four = …
sepp2k 378 Practically a Master Poster

You also need to change the call to qsort to use sizeof(char) instead of sizeof(int), but yes, for chars all you need to change in the compare function is to replace int* with char* when casting the pointers.

For strings you'd want a different logic in the compare function though. If you'd just subtract the strings from each other, you'd sort by the pointer values, which is rarely what you want. So you'd cast the void pointers to char**, then dereference those and pass the resulting char*s to strcmp, so that it compares the contents of the strings.

sepp2k 378 Practically a Master Poster

qsort calls the compare function with pointers to the values as arguments. Since qsort can work with any type of array, those pointers are void pointers. So a comparison function given to qsort must take two (const) void pointers as arguments.

So that's why the signature of compare looks like it does. In the body it then simply casts the void pointers to int pointers (because the compare function knows that the values you're trying to compare are really ints), dereferences them and subtracts the second value from the first.

So the function simply compares two integers by subtracting the second from the first. This will cause a negative number to be returned if the first number is the smaller one, 0 if both are equal and a positive number if the second number is the larger one, which is exactly what's expected of a comparison function given to qsort.

sepp2k 378 Practically a Master Poster

I still need to set a global variable because It carrys over function calls

No, you don't; local variables that are closed over from an outer function do carry over between function calls. Look at this:

def memoize(f):
    cache = {}

    def wrap(x):
        print("Contents of cache: {}".format(cache))
        if x not in cache:
            print("Calculating {}({})".format(f.__name__, x))
            cache[x] = f(x)
        return cache[x]

    return wrap

def double(x):
    return 2 * x

def square(x):
    return x*x

mdouble = memoize(double)        
msquare = memoize(square)

print("Double:")
mdouble(3)
mdouble(3)

print("\nSquare:")
msquare(3)
msquare(3)

Output:

Double:
Contents of cache: {}
Calculating double(3)
Contents of cache: {3: 6}

Square:
Contents of cache: {}
Calculating square(3)
Contents of cache: {3: 9}

As you see both msquare and mdouble have their own cache and those caches persist between calls to msquare and mdouble respectively. So this acts exactly like you want without any globals.