Skip to content
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

[RFC] update object syntax: obj.updateObj(field1 = foo, field2 = "bar") #8180

Closed
timotheecour opened this issue Jul 2, 2018 · 5 comments
Closed

Comments

@timotheecour
Copy link
Member

The following seems quite useful, I wonder whether it's already in stdlib ? If not would that belong in system.nim ?

import macros
import strformat

macro updateObj*(src: typed, n: varargs[untyped]): typed =
  result = newNimNode(nnkStmtList, n)
  for x in n:
    let cmd = fmt"{toStrLit(src)}.{toStrLit(x)}"
    # or: let cmd = $(toStrLit(src)) & "." & $(toStrLit(x))
    result.add(parseStmt(cmd))

# usage:
type Foo=object
  a:string
  b:int
  c:seq[string]
  d:bool

proc test_updateObj*()=
  var opt: Foo
  opt.updateObj(b = 3 - 5, a="asdf", c = @["baz", """ ? """], d=true)
  echo opt
@metagn
Copy link
Collaborator

metagn commented Jul 2, 2018

Heads up: toStrLit(x) is just newStrLitNode(repr(x)), $toStrLit(x) is just repr(x).

This macro could be more generalized in a tap or doto macro as in ruby or clojure and that wouldn't really fit in with the stdlib in my opinion, instead some general utility Nimble package.

@andreaferretti
Copy link
Collaborator

There is also automatic self insertion that, while not the same thing, may be used in similar cases

@dom96
Copy link
Contributor

dom96 commented Jul 3, 2018

I vote for this to be made put in a Nimble package. If it becomes popular enough we can adopt it into the stdlib later.

@timotheecour
Copy link
Member Author

ok, closing in favor of nimble package

@metagn
Copy link
Collaborator

metagn commented Jul 6, 2018

I'm surprised I didn't remember this before, but this is already in the package cascade

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants