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

outplace argument _ #292

Open
timotheecour opened this issue Nov 30, 2020 · 2 comments
Open

outplace argument _ #292

timotheecour opened this issue Nov 30, 2020 · 2 comments
Labels

Comments

@timotheecour
Copy link
Member

timotheecour commented Nov 30, 2020

proposal

Support the outplace argument placeholder _ to convert an inplace algorithm into an outplace one for the common case where the outplace argument is assumed to be initialized to its default value for its (inferred) type.

Example

proc merge[T](result: var seq[T], x, y: openArray[T]) = ...
let x = [1,3]
let y = [2,5]
let a = merge(_, x, y)
let a2 = _.merge(x,y) # also works

# same as:
var a: seq[int]
merge(a, x, y)

# also same as:
import std/sugar
let a3 = seq[int].default.dup(merge(x, y))
  # less readable and not DRY since seq[int] must be specified (can't do type inference here)

Notes

  • the outplace argument can appear in any position, not just the 1st, as its position is given explicitly by _:
proc fn[T](a: seq[T], b: var T) = ...
let a = fn(@[1,2], _) # works
let a2 = @[1,2].fn(_) # also works
  • sugar.dup is still useful in the cases where you need a non-default value for the outplace argument, or when type inference wouldn't be possible, because the generic is only inferred from the outplace argument instead of other arguments.

implementation

  • requires compiler support.
  • in sigmatch, the arguments are implicitly reordered so that _ is matched last, at which point all generic parameters must be bound, or a sigmatch error occurs.

links

@metagn
Copy link
Contributor

metagn commented Dec 6, 2020

I don't mean to delay or complicate anything, but thoughts on this?

proc merge[T](result: var seq[T], x, y: openArray[T]) = ...
let x = [1, 3]
let y = [2, 5]
merge(let a, x, y)
(let a2).merge(x,y) # torn on this one

proc fn[T](a: seq[T], b: var T) = ...
fn(@[1, 2], let a) 
@[1, 2].fn(let a2)

I believe some other language does something like this but I forget

Copy link

This RFC is stale because it has been open for 1095 days with no activity. Contribute a fix or comment on the issue, or it will be closed in 30 days.

@github-actions github-actions bot added the Stale label Dec 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants