3 ms·
Considering how contrived the implementation of this is, there's no wonder it looks terrible in two languages. For example, this Python is both better behaved
by Veedrac 11y ago
Considering how contrived the implementation of this is, there's no wonder it looks terrible in two languages.
For example, this Python is both better behaved and much, much simpler:
import sys
for filename in sys.argv[1:]:
try:
with open(filename, "rb") as file:
word_count = sum(len(line.split()) for line in file)
except IOError as e:
print(e)
else:
print("{}: {}".format(filename, word_count))
I'd suggest you think up an example that justifies its implementation before making such a comparison. If the aim is to make both implementations do the same dance, not just to make them give the same results, even Haskell won't look much different to C++.
- colomon 11y agoYeah, here's a Perl 6 version: #!/usr/bin/env perl6 sub MAIN(*@filename) { for @filename -> $file { say "$file: { +$file.IO.slurp.words } words"; CATCH { default { say "Unable to count words in $file"; } } } }
- lqdc13 11y agoYours doesn't hash unique words though
- Veedrac 11y agoThe original implementation's bucketing was completely irrelevant to the goal - it still ended up counting the number of words, duplicates included.
- lqdc13 11y agoThey're not counting duplicates though... Both perl and C++ one use a hash table.
- Veedrac 11y agoThey use a <word → word frequency> mapping, and then sum the values. This gives the total number of words. The hash table is totally pointless.
- lqdc13 11y agoYou're totally right.
- draegtun 11y agoThe author did have a point he wanted to put across with the hash table - "Obviously, a frequency distribution was not necessary for just the counts, but I did want to highlight basic autovivification" ref: http://www.reddit.com/r/cpp/comments/369lcn/can_c_become_your_new_scripting_language/crcklhr http://www.reddit.com/r/cpp/comments/369lcn/can_c_become_you...
- Veedrac 11y agoThat doesn't feel like a good reason. The author could easily have come up with a better task (eg. count the number of words with more than one occurrence). This allows you to approach the problem in the optimal way in each language.
- colomon 11y agoOoo, I can do that in Perl 6 too. #!/usr/bin/env perl6 sub MAIN(*@filename) { for @filename -> $file { my $bag = $file.IO.slurp.words.Bag; say "$file: { [+] $bag.values } words"; CATCH { default { say "Unable to count words in $file"; } } } }