On Tue, Oct 6, 2020 at 6:32 AM Markus Heukelom <markus.heuke...@gain.pro> wrote:
>
> It appears to me the current proposal does not allow you to write a function 
> that sorts an array of any size:
>
> func SortArray[T comparable](array [??]T, less func(a, b T) bool) [??]T {}
>
> Is it correct that this is not possible? Or is this expressed differently?
>
> To clarify, I am seeking for something like:
>
> func SortArray[T comparable, int n](array [n]T, less func(a, b T) bool) [n]T 
> {}

You are correct that the current design draft does not provide any
mechanism for writing code that is generic across the dimension of an
array.  This is mentioned in the list at
https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#omissions.
I don't think it would be hard to add later if it seems useful.

That said, I don't think your suggested SortArray function would be a
good API.  In Go arrays are passed by value, so this would copy the
entire array into the function, sort it, and then copy the entire
array out.  It is trivial to turn an array into a slice, by writing
a[:], so it would be more natural in Go to write Sort(a[:], less),
which would let the caller decide whether to make a copy or not.


> Here's two other examples that come to mind:
>
> type Number {types ...}
> func DotProduct[T Number, int n](a, b [n]T) T {} // n can be any integer
> func MultMatVec[T Number, rows, cols int](m [rows][cols]T, v [cols]T) [rows]T 
> {}

Agreed.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcV%3DqHvDHmAWw7RmULijAn%3Dh%3DbzjTOk2WJuLZp80fYsByw%40mail.gmail.com.

Reply via email to