6 ms·
Heh, that's actually slightly shorter than this Haskell version: print =<< sum . map read . lines <$> readFile "somefile.txt" Someone can probably golf this
by swift 13y ago
Heh, that's actually slightly shorter than this Haskell version:
print =<< sum . map read . lines <$> readFile "somefile.txt"
Someone can probably golf this shorter, though. =)
- evincarofautumn 13y agoThis defaults Num, Read, and Show to Integer—I try to avoid defaulting because it’s kind of a language wart. And speaking of golf: same length but one fewer import by killing the fmap. print . sum . map read . lines =<< readFile "somefile.txt"
- tome 13y agoMuch clearer. I slightly prefer the following though: ((print . sum . map read . lines) <=< readFile) "somefile.txt"
- evincarofautumn 13y agoPointfree makes more sense for a definition, I think: sumFileLines = print . sum . map read . lines <=< readFile Less so inline because of the excessive parentheses or ($).
- abecedarius 13y agoSure. print sum(map(float, open('somefile.txt')))
- dchichkov 13y agoThat's a bit of cheating, as it removes 'lines' or 'line' from code, decreasing readability. So to be fair you want to add it back: print sum(map(float, open('somefile.txt'))) # over lines or print sum(map(lambda line: float(line), open('somefile.txt'))) Either one is all right, but personally I prefer list comprehension notation. As per Guido: ... and that a more concise notation for anonymous functions would make map() more attractive. Personally, I disagree—I find the list comprehension notation much easier to read than the functional notation, especially as the complexity of the expression to be mapped increases. ...
- abecedarius 13y agoIn Python it's well known that the default iterator on a file gives you the lines. Arguably a function would've been a clearer design, but this is idiomatic in the language we have. As far as map vs. list comprehension, yes, I prefer the comprehension in the cases where map would need lambda. Here that's not the case. Per "as the complexity of the expression to be mapped increases", this expression 'float' is the simplest possible.