nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.41k stars 1.47k forks source link

Better implicit array typing #117

Closed ventor3000 closed 11 years ago

ventor3000 commented 12 years ago

Feature request.

The following code, which implicitly tells Nimrod that vars test and test2 are TAnimalArray:s does not work. Implicit casting of the elements in array to TAnimal should be done.

type TAnimal=object PAnimal=ref TObject

TDog=object of TAnimal
PDog=ref TDog

TCat=object of TAnimal
PCat=ref TCat

TAnimalArray=array[0..2,PAnimal]

proc newDog():PDog = new(result)

proc newCat():PCat = new(result)

proc test(a:openarray[PAnimal])= echo("dummy")

test(newDog(),newCat()) #does not work

var myarray:TAnimalArray=[newDog(),newCat(),newDog()] #does not work

var myarray2:TAnimalArray=[newDog(),newDog(),newDog()] #does not work either

AdrianV commented 12 years ago

+1 It is annoying to cast back to PAnimal every time

reactormonk commented 11 years ago

Nicely formatted:

type
  TAnimal=object {.inheritable.}
  PAnimal=ref TObject

  TDog=object of TAnimal
  PDog=ref TDog

  TCat=object of TAnimal
  PCat=ref TCat

  TAnimalArray=array[0..2,PAnimal]

proc newDog():PDog = new(result)
proc newCat():PCat = new(result)
proc test(a:openarray[PAnimal])=
  echo("dummy")

test(newDog(),newCat()) #does not work
var myarray:TAnimalArray=[newDog(),newCat(),newDog()] #does not work
var myarray2:TAnimalArray=[newDog(),newDog(),newDog()] #does not work either

Yep, implement covariance :-P