nim-lang / RFCs

A repository for your Nim proposals.
135 stars 26 forks source link

Allow to specify type for unpacking assignment #339

Closed al6x closed 10 months ago

al6x commented 3 years ago

Currently this code would fail:

let pair: (int, int) = (1, 2)
let (a, b) = (1, 2)

let (c, d): (int, int) = (1, 2) # <= Error

Would be nice if it would work.

metagn commented 3 years ago

I would say let (c: int, d: int) looks better and you have to type less (and you don't need to support auto) but the structure of the AST for tuple unpacking would have to breakingly change for that (there is a reserved AST spot for a type which would only work for let (c, d): (int, int)), plus let (c, d: int) could be interpreted as meaning the same thing as let (c: int, d: int) (because of other parts of the language that do this), so you could have to support let (c; d: int). It would also conflict with any intuitive possible method of named tuple unpacking.

timotheecour commented 3 years ago

let (c: auto, d: int)

metagn commented 3 years ago

Partial current workaround:

((var c: int; c), (var d: int; d)) = (1, 2)

Has the caveat of having to be var and not let, but allows mixing new variables with old ones. The ugliness can be mediated with a template

template newVar(name, ty): untyped =
  var name: ty
  name

var a = false

(a, newVar(b, cstring), newVar(c, int)) = (true, "abc", 2)
echo a # true
echo b # abc
echo c # 2
timotheecour commented 3 years ago

how about simply:

var a = 1
(a; let b; var c) = (1,2,3)

and to allow types:

var a = 1
(a; let b: int; var c) = (1,2,3)

the syntax is as simple and flexible as it gets.

grouping by type is possible too:

var a = 1
var b = 1
(a, b; let b, c: int; let c, d: float) = (1,2,3,4,5.0,6.0)

; is used before a let or var inside destructuring. Makes it simple.

metagn commented 3 years ago

Sorry, I wasn't proposing anything or offering an alternative to the proposal, I was just saying how it's possible to get the semantics in current Nim. The only issue with getting the semantics beyond aesthetics is that you have to use var.