Hi,
First I want to introduce myself. I found today Nimrod because of a thread in dlang forum and find it very interesting since its syntax looks IMHO much cleaner. My background is mainly pascal (starting with USCD pascal and turbo pascal to delphi, freepascal) and Haxe since 4 years. For targets like JavaScript, Flash, php, neko I am very happy with Haxe, but for system level programming I need something more powerful. The development of (and with) ObjectPascal is not satisfying anymore. I am convinced that OO is often misused where a better generic type system would generate better code. C++ is not an option, because I burned my fingers in the past. I looked into D, which I also find very interesting. And now I am playing around with Nimrod and I am quite impressed from my first tests, but need to ask some questions. I hope this is the right place to do.
I am trying to do:
which gives an error, which I don't understand because I can do
How can I do this correctly ?
Best,
Adrian.
Welcome Adrian! I'm glad you are liking Nimrod :)
Instead of writing type(arr[0]) you should write T. Just like you do in the params for your first function. However, you are making the arr parameter a generic type, what I think you want is to tell the compiler that it's an array, you can do so like this:
proc first[I, T](arr: array[I, T]): T =
return arr[0]
var a = [1,5,10,15]
echo a.first
In this example the I refers to the size of the array and the T is the type of the values in the array. If you want to have dynamic length arrays you can use sequences (http://build.nimrod-code.org/docs/manual.html#array-and-sequence-types).
I hope this helps.
Regards, Dominik.
Hello Dominik,
Thanks for your help. This works so far, but what can I do if I want it to be more generic. Lets say T is a collection of E and I want to create a proc which works on T and returns an E ?
proc doSomething[T, E] (col:T):E =
return col[0]
this does not seem to work - I get an error: cannot instantiate: 'E'. Is there a way to infer the return type in a generic proc ?
You can instantiate the types by calling the doSomething function like so:
doSomething[seq[int], int](col)
doSomething[seq[int], int](col)
looks a little bit clumsy. Now after some reading, I would prefer to write the Implementation of doSomeThing as a template and instantiate it with all possible collections I need.
But anyway - I took some time and looked through the sources yesterday and I really like Nimrod, because it is easy to understand whats going on. I will try to port some of my code to Nimrod and see how it behaves.
Cheers, Adrian