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

typedesc cannot be used as a type converter #8403

Closed
bluenote10 opened this issue Jul 22, 2018 · 2 comments
Closed

typedesc cannot be used as a type converter #8403

bluenote10 opened this issue Jul 22, 2018 · 2 comments

Comments

@bluenote10
Copy link
Contributor

Might be related to #7160, but maybe worth tracking on its own. It looks like it is not possible to use typedescs for type conversions:

proc sum*[T](s: seq[T], R: typedesc): R =
  # sum which aggregates into a different result type
  var sum: R = 0
  for x in s:
    sum += R(x)
  return sum

echo @[1, 2, 3].sum(float)

Errors with Error: type expected in the conversion line. The same does work with generics

proc sum*[T, R](s: seq[T]): R =
  var sum = R(0)
  for x in s:
    sum += R(x)
  return sum

echo sum[int, float](@[1, 2, 3])

but this is much less elegant in some API design cases (e.g. in this case because having an overload sum[T] (implicit return type) and sum[T, R] (explicit return type) overload at the same time would be disallowed due to result type overloading).

I just noticed that there is a simple work-around for the issue though, which indicates that this is probably not a fundamental issue with typedescs. Introducing a dummy generic works:

template dummyConvert[T, R](x: T): R = R(x)

proc sum*[T](s: seq[T], R: typedesc): R =
  var sum: R = 0
  for x in s:
    sum += dummyConvert[T, R](x)
  return sum

echo @[1, 2, 3].sum(float)
@Araq
Copy link
Member

Araq commented Jul 22, 2018

Errors with Error: type expected in the conversion line.

Wierd error message, but doesn't this conversion mean that you want to convert x to a typedesc? If not, how would one do the conversion to a typedesc? Via type(R)(x)? typedesc is terrible. :-/

@zah
Copy link
Member

zah commented Jul 22, 2018

@Araq, what?

A bound typedesc paramter such as R in the example is a concrete type. It's just a bug that the conversion doesn't work (there is a missing skipTypes somewhere).

In fact, there is a simpler work-around. The problem goes away if you give the R type a new name inside the proc:

proc sum*[T](s: seq[T], R: typedesc): R =
  # sum which aggregates into a different result type
  type RR = R
  var sum: R = 0
  for x in s:
    sum += RR(x)
  return sum

echo @[1, 2, 3].sum(float)

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