4 ms·
I guess this is what he meant to write, programming language permitting: int Total() { return dice.Sum(die => die.FaceValue); }
by DougBTX 16y ago
I guess this is what he meant to write, programming language permitting:
int Total()
{
return dice.Sum(die => die.FaceValue);
}
- jkkramer 16y agoClojure: (reduce + (map face-value dice))
- arethuza 16y agoOr: ( loop for die in dice sum ( face-value die )) Been a while since I've done any lisp, but pretty sure that is how you would probably do it.
- amalcon 16y agoCould also do something like: (reduce + (map face-value dice))
- ambition 16y agoWhat language is this?
- beagle3 16y agoor, in APL/K style languages, +/dice`facevalue
- jerf 16y agoIt should be pointed out, because I fear people are missing this point, that while the instantiation of his point is language-specific, the general point holds regardless. In Haskell, to take the opposite extreme, "foldl (+) (map dieSum dies) 0" would be idiomatic (or would be if the sum function wasn't built in to Prelude as well but I feel that's cheating too much), whereas the closest equivalent to the loop approach in C++ would be grotesque and unidiomatic. How grotesque would be up to the user; you could go all the way to having the die values in an array and iterating an index through them if you like, but it'll make the C++ version of that look pretty sane. The exact algorithms aren't the point. It's really something more like "stay idiomatic in the language you are in and keep it simple". Another example is when people start going nuts with lambda in Python; you're really not supposed to do that and there is almost always a better way that doesn't involve lambdas.
- DougBTX 16y agoYes, staying idiomatic is a good idea, it's worth pointing out explicitly. As a tangent, while the original author was trying to abstract away the loop, I feel he left too many fragments of the loop behind, such as the start and end conditions. As such, I don't think the sum function is cheating too much, and is in fact the goal. I might describe the Total as "the sum of the dies' face values," instead of the more verbose: "the sum of the dies' face values, starting from the first die and ending at the last die." In a sense, this runs parallel to your reminder to stay idiomatic: when you sum a list of things, it is common to add them all together, not just some subset. It is this shared understanding which lets us be succinct. Though I do fear that I'm preaching to the choir :-)
- ecaradec 16y agoThe problem is that there is more than one idiomatic c++
- ntoshev 16y agoPython: sum(d.faceValue() for d in dice)