-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
take/takeWhile iterators for Counttables #13428
Conversation
Not that count = 0
for (word, count) in wordFrequencies:
echo alignLeft($count, 8), word
inc(count)
if count == 10:
break It does not seem to need access the internal data structures of tables |
What would actually need access to the internal structure would be |
Seems pretty confusing to name this If you really want to champion this PR, you will need to add a changelog entry, a |
I think you have to start with the test, but consider that you can just sort the |
this works generically: import macros
# `macro takeN(x: ForLoopStmt, n: int): untyped =` is currently not allowed but could be
macro takeN(x: ForLoopStmt): untyped =
var body = x[^1]
let inputs = x[^2][1]
doAssert inputs.len == 2
let elems = inputs[0]
let maxIter = inputs[1]
let count = genSym(nskVar, "count")
expectKind x, nnkForStmt
body.add quote do:
`count`.dec
if `count` == 0: break
var newFor = newTree(nnkForStmt)
for i in 0..x.len-3: newFor.add x[i]
newFor.add elems
newFor.add body
result = quote do:
var `count` = `maxIter`
if `count` > 0: `newFor`
echo result.repr
when isMainModule:
{.push experimental: "forLoopMacros".}
import tables, sequtils
proc main =
var t = toTable({1:1, 2:2, 3:3, 4:4})
echo t
for b in takeN (pairs(t), 1+1): echo b
for a,b in takeN (pairs(t), 1+1): echo (k: a, v:b)
# echo toSeq(takeN (pairs(t), 2)) # limitation: we can't compose
main() allowing |
I was trying to write an implementation for word frequency but didn't come up with an elegant solution to print the 10 most frequent words. See also discussions in the Nim forum Idiomatic sequence functions. I thought it would be best to extend the tables library itself as in there we have direct access to the internal data structure of CountTables.
The word frequency code could be more succinctly written as:
The essential part being
wordFrequencies.take(10)
. The resulting binary would be more efficient, too.I think the PR is not complete. There should be the same functions for CountTableRefs and maybe other table types. Although I think take/takeWhile make most sense for CountTables. Maybe also take and takeWhile procs that return sequences had to be added. I am not sure about that though. Just let me know what you think of it and if need be how I should adapt the PR.