Well I want to learn C++ and at the moment I'm only familiar with PHP and Javascript. And I thought a good way to start learning would be to transfer methods in PHP to C++.
So basically I want the code snippets below in C++
The post with the best comments will get a big green tick.
Also, if you know of a good beginners tutorial please leave a comment.
So here are the bits of code I want in C++
First
$array = array('I\'m', 'learning', 'C++');
foreach($array as $word){
echo $word.' ';
}
Second
function foo($num,$ber, $add = true){
if(is_numeric($num) && is_numeric($ber)){
if(!$add){
echo $num*$ber;
}
else{
echo $num + $ber;
}
}
else{
echo 'They aren\'t numbers!';
}
}
foo(2,4, false);
I'm skeptical about the pedagogical usefulness of translating this into C++. Just translating the above code may not be too useful. Take your first example, where you loop over an array of strings and print out each word - sure, I could translate this into C++ using an std::vector<std::string>, iterate over the vector and output each string to stdout. But is that really going to teach you anything? I could also use a C array of const char* pointers, iterate over that and call printf on each one. But is that really going to teach you anything?
Since you already know how to code in PHP and Javascript, you're obviously aware of basic programming concepts like variables, loops, conditionals, etc. But C++ is a dramatically different language than either PHP or Javascript. For one thing, it's statically typed. For another thing, it requires manual memory management. So I think rather than trying to translate PHP code to C++, you'd be better off reading a good introductory book to C++.
never try to learn any complex subject by 'translating' from another one, no matter how well you know the old one.
You'd only get inconsistent concepts, with the limitations of both and the advantages of none.
I think you'd be much better off if you tried to figure it out and asked questions you had about it along the way.
Related
I'm trying to write more functional code in PHP without any helper libraries.
I need to return some JSON that includes the results of a transformed array AND the count of that array (for convenience on the data consumer end). Since you're not supposed to use variables in FP, I'm stumped on how to get the count of the array without recalculating/remapping the array.
Here's an example of what my code currently looks like:
$duplicates = array_filter( get_results(), 'find_duplicates' );
send_json( array(
"duplicates" => $duplicates,
"numDuplicates" => count( $duplicates )
) );
How can I do the same without storing the results of the filter in a temporary variable to avoid running array_filter() twice?
But first, acknowledge the following...
"Since you're not supposed to use variables in FP..." – that's a ludicrous understanding of functional programming. Variables are used constantly in functional programs. I'm guessing you saw point-free functional programs and then imagined that every program can be expressed in such a way...
the receiver of the JSON could easily get the number of duplicates using JSON.parse(json).duplicates.length because every Array in JavaScript has a length property – it's arguably silly to attach a numDuplicates in the first place. Anyway, let's assume your consumer has a specific API that requires the numDuplicates field...
functional programming is concerned with things like function purity – maybe you've simplified your code in your post (which is bad; don't do that) or that is in fact your actual code. In such a case, get_results() and send_json functions are impure; send_json has an obvious (but unknown) side effect (the return value is not used) — You ask for a functional solution but you have other outstanding non-functional code... so...
There's nothing wrong with the code you have. Sometimes removing a point (variable, or argument), it hurts the readability of the code. In your case, this code is perfectly legible. It is at this point that I feel you're only trying to shorten the code or make it more clever. Your intention is to improve it, but I think you'd actually harm it in this case.
What if I told you...
a variable assignment can be replaced with a lambda? 0_0
(function ($duplicates) {
send_json([
'duplicates' => $duplicates,
'numDuplicates' => count($duplicates)
});
}) (array_filter(get_results(), 'find_duplicates'));
But that made the code longer.. and there's added abstraction which hurts readability T_T In this case, using a normal variable assignment (as in your original code) would've been much better
Combinators
OK, so what if you had some combinators at your disposal to massage the data into the desired shape?
function apply (...$xs) {
return function ($f) use ($xs) {
return call_user_func($f, ...$xs);
};
}
function identity ($x) { return $x; }
// hey look, mom! no points!
send_json(
array_combine(
['duplicates', 'numDuplicates'],
array_map(
apply(
array_filter(get_results(), 'find_duplicates')),
['identity', 'count'])));
Did we achieve anything other than writing the weirdest PHP you or anyone else has probably seen? Not to mention, the input is strangely nested in the middle of the expression...
remarks
I'm nearly certain that you'll be disappointed with this answer (or disagree with me), but I'm also pretty confident that you're not sure what you're looking for. A guess: you saw functional programming that "doesn't use variables" and assumed that's how all programs can and should be written; but that's just not the case. Sometimes using a variable or two can dramatically improve the readability of a given expression.
Anyway, all of this is truly beside the point because attaching numDuplicates is arguably an anti-pattern in JSON anyway (point #2 above).
I want to pass this input
$string = "AL & JRL buSineSS CENTRE is the best";
Expected Result:
AL & JRL Business Centre Is The Best
I have tried the code below but it converts everything.
mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
So I take it you just want potential acronyms to be ignored, correct? Well, there are a few thoughts. First, you could make a script that ignores anything with 3 or less letters. That's not a great solution, in my opinion. What about "it", "the", etc.? The second is using a dictionary of known words to run ucwords() on. Yuck - that'd be incredibly taxing for such a seemingly simple task!
I'd recommend simply ignoring anything that is all-caps. This way, no matter what the acronym is (or the length), it'll ignore it. Something like this may suffice:
$phrase = "Hello this is a TeSt pHrAse, to be tested ASAP. Thanks.";
$chunks = explode(" ", $phrase);
$result = "";
foreach($chunks as $chunk){
if(!ctype_upper($chunk)) {
$result .= ucwords($chunk) . " ";
} else {
$result .= $chunk . " ";
}
}
$result = rtrim($result);
Result:
Hello This Is A Test Phrase, To Be Tested ASAP. Thanks.
This isn't the most elegant solution, this is just something I've kind of thought about since reading your question. However, if you know your acronyms will be capitalized, this will skip them entirely and only title-case your actual words.
Caveats
The example provided above will not work with an acronym joined to a word by a dash, underscore, etc. This only works on spacing. You can easily tweak the above to your needs, and make it a little more intelligent. However, I wanted to be very clear that this may not fulfill all needs!
Also, this example will come up short in your example phrase. Unfortunately, unless you use a dictionary or count string lengths, this is the closest you'll get. This solution is minimal work for a great deal of functionality. Of course, a dictionary with comparisons would work great (either a dictionary of acronyms or words, either way) - but even then it would be very difficult to keep up to date. Names will throw off a dictionary of words safe to change to title-case. Less commonly used acronyms surely won't be in a dictionary of acronyms. There are endless caveats to all solutions unfortunately. Choose what's best for you.
Hope this helps. If you have any further questions please comment and I'll try the best I can to help.
Randomness
One last thing. I used ucwords(). Feel free to use whatever you want. I'm sure you already know the difference, but check this out:
Best function for Title capitlization?
Always good to know exactly what tool is best for the job. Again, I'm sure you know your own needs and I'm sure you chose the right tool. Just thought it was an interesting read that could help anyone stumbling upon this.
Final Thoughts
You could use a combination of the above examples to custom tailor your own solution. Often it's very satisfactory to combine methods, thus reducing the downsides of each method.
Hope this helps, best of luck to you!
I am trying to apply a spell check to users' queries using a similar system to Google's "Did you mean: " using PHP.
Is there a way to do this with a plugin or API? If not, what are your suggestions?
Possible Simplified Code?
API
<?php
function checkSpelling($query) {
//Boolean where false value means a word is spelt wrong in string
return file_get_contents("http://foo.com/?q=$query");
}
function getSuggestions($query) {
//data with suggestions for word
return file_get_contents("http://foo.com/?q=$query");
}
if (!checkSpelling(foo)) {
echo getSuggestions(foo);
}
?>
Plugin
<?php
require("plugin.php");
//plugin functions similar to the functions above are defined already
if (!checkSpelling(foo)) {
echo getSuggestions(foo);
}
?>
NOTE: Pspell is not an option because I have PHP 5.X.X and am unable to install it on the server.
NOTE: PHP Spell Check does not have the disired interface.
Using Levenshtein Distance would be the first solution that come to mind and I would expect a hybrid approach of auto-complete, a common misspelling keyword set and then Levenshtein and/or SOUNDEX would get you in the usability ballpark that you're looking for. And yeah, it's a bit of a project.
Another piece of advice that comes to mind with things like this is to ask yourself. "What is it that I'm really trying to do?"
Often times a fullblown Google grade solution may be like sandblasting a soup cracker because your use case isn't theirs. If the goal is getting Visitor A to Information B in a nice easy way, they're are a number of ways to accomplish that that may be simpler and/or better for you instead of trying to reverse engineer something verbatim.
I was reading sourses of OpenCart and phpBB engines and noticed that there are lot of strings (sometimes full screen listings) with repeated code, which differs only in one parameter. Such as:
$this->data['button_cart'] = $this->language->get('button_cart');
$this->data['button_wishlist'] = $this->language->get('button_wishlist');
$this->data['button_compare'] = $this->language->get('button_compare');
$this->data['button_continue'] = $this->language->get('button_continue');
I am thinking about using function for generating code using paterns, and then eval() it.
Some such function:
function CodeGenerator($patern, $placements_arr){
$echo_str = '';
foreach($placements_arr as $placement){
$echo_str .= str_replace('=PATERN=', $placement, $patern);
}
if(substr($echo_str, -1)!==';'){
$echo_str .= ';'; # for correct eval() working
}
return $echo_str;
}
And then for large repeated blocks of code with same patern:
$patern = "$this->data['=PATERN='] = $this->language->get('=PATERN=');";
$placements_arr = array('button_cart', 'button_wishlist', 'button_compare', 'button_continue');
$echo_str = CodeGenerator($patern, $placements_arr);
eval($echo_str);
I want to understand PRO and CONTRA of such design, because I am thinking about using such design in my future development.
The only problem I see here now - a bit more slow execution. Any others?
Well for the block of code you have shown you could rewrite it like this
$params = array('button_cart', 'button_wishlist', 'button_compare', 'button_continue');
foreach($params as $param)
$this->data[$param] = $this->language->get($param);
You are writing out the parameters anyways, so I cannot see one benefit to your code over something like what I have shown above. Plus this is only 3 lines of code vs 11 of yours, and mine is instantly readable
in 99.9% of the code you write, you can write it without eval. There are some corner cases where eval makes sense, but in my 5 years of coding php so far I have used it maybe one or 2 times, and if I went back to the code I could probably rewrite it so It didn't.
If I had to maintain a project with code that you wrote, I would be tearing my hair out. Just look at what OpenCart wrote, and look at what you wrote. Which one is easier to understand? I actually have to look at your code a few times to understand what it is doing, I can skim over the OpenCart code and instantly understand what is happening.
Maintainability - if that's a word - might be a small concern. I would despise such a construct because it seems unnecessarily complex. I have inherited many - a - poorly designed php sites working as a web developer and in just about zero cases can I recall it being considered a nuisance to have to spool through a list of var assignments like above. However, I would become infuriated by having to deal with weird lazy functions that attempt to escape the banalities of repetitive typing.
In the end you're talking about fractions of a second for processing so that's hardly an argument for doing something like this. And if the microseconds are a concern, use a caching mechanism to write to flat text and wipe out all redundant processing all together.
Hey, my 2 cents. If it's your project and you don't expect anyone else to maintain it then knock yourself out.
I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.
Some examples:
Class naming convention to handle namespaces: Part1_Part2_ClassName maps to file Part1/Part2/ClassName.php
if ( count($arrayName) ) // handles $arrayName being unset or empty
Variable function names, e.g. $func = 'foo'; $func($bar); // calls foo($bar);
Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...
Apply liberally for fun and profit:
Iterators in foreach loops. There's almost never a wrong time.
Design around class autoloading. Use spl_autoload_register(), not __autoload(). For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.
Typehint everywhere. Use assertions for scalars.
function f(SomeClass $x, array $y, $z) {
assert(is_bool($z))
}
Output something other than HTML.
header('Content-type: text/xml'); // or text/css, application/pdf, or...
Learn to use exceptions. Write an error handler that converts errors into exceptions.
Replace your define() global constants with class constants.
Replace your Unix timestamps with a proper Date class.
In long functions, unset() variables when you're done with them.
Use with guilty pleasure:
Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.
Use output buffers for assembling long strings.
ob_start();
echo "whatever\n";
debug_print_backtrace();
$s = ob_get_clean();
Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:
Magic methods (__get, __set, __call)
extract()
Structured arrays -- use an object
My experience with PHP has taught me a few things. To name a few:
Always output errors. These are the first two lines of my typical project (in development mode):
ini_set('display_errors', '1');
error_reporting(E_ALL);
Never use automagic. Stuff like autoLoad may bite you in the future.
Always require dependent classes using require_once. That way you can be sure you'll have your dependencies straight.
Use if(isset($array[$key])) instead of if($array[$key]). The second will raise a warning if the key isn't defined.
When defining variables (even with for cycles) give them verbose names ($listIndex instead of $j)
Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.
Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using Zend Framework's naming conventions because they feel right to me.
Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the full backtrace.
Fortunately, namespaces are in 5.3 and 6. I would highly recommend against using the Path_To_ClassName idiom. It makes messy code, and you can never change your library structure... ever.
The SPL's autoload is great. If you're organized, it can save you the typical 20-line block of includes and requires at the top of every file. You can also change things around in your code library, and as long as PHP can include from those directories, nothing breaks.
Make liberal use of === over ==. For instance:
if (array_search('needle',$array) == false) {
// it's not there, i think...
}
will give a false negative if 'needle' is at key zero. Instead:
if (array_search('needle',$array) === false) {
// it's not there!
}
will always be accurate.
See this question: Hidden Features of PHP. It has a lot of really useful PHP tips, the best of which have bubbled up to the top of the list.
There are a few things I do in PHP that tend to be PHP-specific.
Assemble strings with an array.
A lot of string manipulation is expensive in PHP, so I tend to write algorithms that reduce the discrete number of string manipulations I do. The classic example is building a string with a loop. Start with an array(), instead, and do array concatenation in the loop. Then implode() it at the end. (This also neatly solves the trailing-comma problem.)
Array constants are nifty for implementing named parameters to functions.
Enable NOTICE, and if you realy want to STRICT error reporting. It prevents a lot of errors and code smell: ini_set('display_errors', 1); error_reporting(E_ALL && $_STRICT);
Stay away from global variables
Keep as many functions as possible short. It reads easier, and is easy to maintain. Some people say that you should be able to see the whole function on your screen, or, at least, that the beginning and end curly brackets of loops and structures in the function should both be on your screen
Don't trust user input!
I've been developing with PHP (and MySQL) for the last 5 years. Most recently I started using a framework (Zend) with a solid javascript library (Dojo) and it's changed the way I work forever (in a good way, I think).
The thing that made me think of this was your first bullet: Zend framework does exactly this as it's standard way of accessing 'controllers' and 'actions'.
In terms of encapsulating and abstracting issues with different databases, Zend_Db this very well. Dojo does an excellent job of ironing out javascript inconsistencies between different browsers.
Overall, it's worth getting into good OOP techniques and using (and READING ABOUT!) frameworks has been a very hands-on way of getting to understand OOP issues.
For some standalone tools worth using, see also:
Smarty (template engine)
ADODB (database access abstraction)
Declare variables before using them!
Get to know the different types and the === operator, it's essential for some functions like strpos() and you'll start to use return false yourself.