3 ms·
I program mainly in C++, and I often start off writing things as: for (auto x : someContainer) { //do something with x } But inevitably, I end up needing
by thewebcount 7y ago
I program mainly in C++, and I often start off writing things as:
for (auto x : someContainer) { //do something with x }
But inevitably, I end up needing either an iterator pointing to a particular item at the end, or I need an index to pass to some other function, and this style makes that impossible. Perhaps it's just the domain I work in, but even after years of trying to make this work, it still only works about half the time for what I'm doing.
- eru 7y agoIn Haskell map someFunction listOfValue if you need an index: map someOtherFunction (zip [0..] listOfValues) Python uses 'enumerate' to similar effect. Not sure if C++ has an equivalent?
- a1369209993 7y agoYou can also use: zipWith someOtherFunction [0..] listOfValues # , since someOtherFunction is likely to be # :: (Int -> Value -> Stuff) rather than # :: ((Int,Value) -> Stuff) . zipIndex f = zipWith f [0..] # is also often useful.
- eru 7y agoYes. I wanted to keep things simpler for people who don't speak Haskell; and show off composition of simpler combinators to build more exciting things at the same time. In eg OCaml you have to use something like zipIndex (but implemented differently) or mapWithIndex, because they don't do lazy data structures by default. (And in eg Python their lazy sequences come with lots of caveats because they are not referentially transparent.)
- hellofunk 7y agoWhy not just pass the reference instead of an iterator or index? That’s what I do the best majority of the time. It’s rare that I actually need a specific iterator or pointer. Just change your loop to auto& x.
- bmn__ 7y agohttp://p3rl.org/each http://p3rl.org/each while (my ($index, $value) = each @list) { ... } https://docs.raku.org/routine/kv#class_List https://docs.raku.org/routine/kv#class_List for @list.kv -> $index, $value { ... }