6 ms·
The author uses Go in this example, and they're really just struggling against the language. This is a pretty good example of why choice of language matters: in
by saagarjha 8y ago
The author uses Go in this example, and they're really just struggling against the language. This is a pretty good example of why choice of language matters: in C++ this could be a simple, linear pass through the array with an std::unordered_set storing visited elements, with an optional std::remove_if/std::erase at the end if they wanted to actually get rid of the elements. All done in linear time, space overhead, and likely with shorter and faster code.
- Nimelrian 8y agoYup, you can implement the whole ordeal in C++ like this: int main(int argc, char** argv) { std::vector<std::string> strings{ "apple", "cAt", "cat", "Dog", "apple", "dog", "Cat", "Apple", "dOg", "banana", "cat", "dog", "apple", }; strings.erase( std::remove_if( std::begin(strings), std::end(strings), [seen = std::unordered_set<std::string>{}](std::string_view str) mutable { std::string lower = ""; std::transform(std::begin(str), std::end(str), std::back_inserter(lower), ::tolower); if (seen.find(lower) == std::end(seen)) { seen.insert(lower); return false; } return true; } ), std::end(strings) ); for (auto& str : strings) { std::cout << str << "\n"; }; }
- johannkokos 8y agoif (seen.find(lower) == std::end(seen)) { seen.insert(lower); return false; } You can just return seen.insert(lower).second as insert function return a pair<iterator, bool>
- Nimelrian 8y agoAnd today I learned something new. Been a long time since I wrote my last lines of C++ anyway.
- rndgermandude 8y agoBonus points for using emplace() instead of insert
- nicoburns 8y agoYeah, this is definitely the downside to Go. You can write more or less the same code as your C++ in Rust like this: use std::collections::HashSet; fn main () { let strings = vec![ "apple", "cAt", "cat", "Dog", "apple", "dog", "Cat", "Apple", "dOg", "banana", "cat", "dog", "apple", ]; let mut set : HashSet<&'static str> = HashSet::new(); let strings : Vec<&str> = strings .into_iter() .filter(|string| set.insert(string)) .collect(); println!("{:?}", strings); } (runnable snippet: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7d19d63ac220173cc7a40d2695841b69 https://play.rust-lang.org/?version=stable&mode=debug&editio...) EDIT: updated to make use of the fact that `set.insert` returns a boolean.
- johannkokos 8y agoJust like C++, your filter can be simplified like, filter(|string| {set.insert(string)} as insert return a bool.
- nicoburns 8y agoOo, I didn't realise that. Super handy. I've updated my snippet to make use of your suggestion :)
- DougBTX 8y agoThe output form this is a little different form the article, as it additionally requires: * that the uniqueness check is done case-insensitively, * that the casing from the first instance of the string in the input array should be used in the output, and * that the output should be ordered based on the order of the first instance of the string in the input array Possibly an unusual set of requirements (I'd generally expect that if removing duplicates from a list, that the output order wouldn't matter) but hey, different problems have different requirements. The desired output is: apple cAt Dog banana while that code snippet produces: apple cAt cat Dog dog Cat Apple dOg banana
- 8y ago
- rndgermandude 8y agoThis is good enough for "small" arrays, but I wouldn't wanna run it on really large ones. You double the space with those lowercased copies + some extra space for the set itself. And you'll also spend a lot of time lowercasing the strings and std::hash'ing them for the set.
- slavik81 8y agoYou need to be careful with C's tolower. It takes a signed integer, and negative values are undefined behaviour. It would be safer to cast to unsigned char before calling tolower. https://en.cppreference.com/w/cpp/string/byte/tolower https://en.cppreference.com/w/cpp/string/byte/tolower
- lqet 8y agoThis is a bit like saying that English is a language superior to Danish, because there are better books out there in English. I don't think this has anything to do with the language, it just happens that C++ ships with a much bigger standard library than Go.
- Nimelrian 8y agoIt's much easier to implement in Javascript, too, even though JS has a much smaller standard library. The main problem is Go's lack of generics.
- bryanrasmussen 8y agoindeed, currently the standard library of JS is incredibly small.
- johannkokos 8y ago> it just happens that C++ ships with a much bigger standard library than Go. I thought go had much bigger standard library. Go has archive, compression, crypto, database, encoding, hash, html, and net etc.
- icebraining 8y agoIt does have to do with the language. Writing a generic Set type is trivial in many languages, yet hard in Go.
- saagarjha 8y agoKeep in mind that I’m not saying that C++ is a better language than Go here: I’d need a lot more evidence than an array deduplication routine to prove this. I’m just saying that Go is ill-suited for this particular task as compared to C++, and the author is struggling with this as they go through with implementing their algorithm; this leads them to settle on a clumsy and inefficient “solution” because there isn’t really a good alternative in the confines of the language that they chose. (FWIW, C++ does have a good standard library for implementing algorithms but this doesn’t really come into play here, since we’re not doing anything advanced. Any language with a set and filter would do the job. And for the record, I do think that C++ is a better language than Go, but I’m not going to argue it here because I don’t know the latter well enough to be confident in my viewpoint and don’t have enough space here to discuss it here if I did.)
- kurtisc 8y agoWhat do you do if you're in a Go project and need to implement this, though? The complexity of FFIs and the maintenance expense of adding another language/compiler is worse than having to work against the language.
- twic 8y ago> What do you do if you're in a Go project and need to implement this, though? Learn from your mistakes.
- andrewla 8y agoThis is the author's choice to make the problem hard -- Go has a built-in map type that works fine for this, and produces code as compact as the C++ version, and is also O(n): seen := make(map[string]bool) for n, s := range array { if seen[strings.ToLower(s)] { array[n] = "" } else { seen[strings.ToLower(s)] = true } }
- earthboundkid 8y agoCode golf: https://play.golang.org/p/mZf5KoAN_87 https://play.golang.org/p/mZf5KoAN_87
- rndgermandude 8y agoDon't calculate strings.ToLower() twice and skip over s == "" to avoid the map lookups and some assignments when already tombstoned and you'll save a lot of time. seen := make(map[string]bool) for n, s := range array { if s == "" { continue } lower := strings.ToLower(s) if seen[lower] { array[n] = "" } else { seen[lower] = true } }
- minitech 8y agoHow can an element be already tombstoned? Isn’t that the first loop, making only one pass?
- wffurr 8y agoDoes Go just warp people's view of what's possible in programming languages? This is a trivial problem to solve for arrays on any data type, but the author can only think about solving it with strings and for whatever bizarre reason can't write out the name "hash set" for the simplest, most general and performant solution?
- klibertp 8y agoYes. Or more precisely, any language puts various limits on what you can easily and conveniently express - in the strict sense, everything you can implement in one language you can implement in all of them as long as they're Turing-complete. However, the amount of effort required to express different things varies between the languages very significantly, and the users tend to confine their thinking to the most directly-supported features of the language they use, as they are most convenient to use most of the time. The term to search for is the "Blub paradox". Go is a language which consciously limits the expressive power of the language in some areas, with the goal of simplifying the implementation and reducing the complexity of codebases written in Go (trading that for repetition). We'll see in 20 years how that plays out. Anyway, constraining oneself to a single language is never good. Learning other languages widens the horizons of what you can imagine implemented (and how), also in your original language. I wish more people - especially starry-eyed fans of this or that language - learned about this fact... :)
- Gene_Parmesan 8y ago> Blub I love the blub paradox story[0]. If you hadn't mentioned it, I was going to. The central idea is, each language lives at a particular spot on a 'power spectrum' -- perhaps 'expressiveness spectrum' is more accurate since theoretically any Turing-equiv lang is technically as powerful as the others. When you look down the power spectrum, at less-expressive languages, it's easy to scoff and say "I can't believe that language is missing Feature X of my chosen language." But when you look up the spectrum (and in the article, LISP is the example given), the more powerful features in that language just look like nonsense. The money quote is "Blub is good enough for him, because he thinks in Blub." For me, my primary language is C#. When I look at Go, I can't help but think "I can't believe it doesn't have generics, how can anyone get anything done in it?" But when I look at LISP metaprogramming, I get uncomfortable with my lack of understanding. Luckily I am a language nerd so I force myself to experience languages at all ends of the spectrum. Highly recommended read. [0]: http://www.paulgraham.com/avg.html http://www.paulgraham.com/avg.html