how to write methods for a generic Matrix[float64 constrained by Addable]?

88 views
Skip to first unread message

Jason E. Aten

unread,
Sep 9, 2023, 6:39:51 PM9/9/23
to golang-nuts
New to generics... how can I write a method for a Matrix[float64] that uses a math function that expects a float64?   I get:

./slurp1.go:936:18: cannot use m.At(i, j) (value of type float64 constrained by Addable) as float64 value in argument to math.IsNaN

Casting it to float64() does not change this error(!)

here is the essentials:

type Addable interface {
    ~complex128 | ~complex64 | ~float64 | ~float32 |
        ~byte | ~uint16 | ~uint32 | ~uint64 |
        ~int8 | ~int16 | ~int32 | ~int64 | ~int
}

type Matrix[T Addable] struct {
    Nrow int
    Ncol int
    Dat        []T
}
...
func (m *Matrix[float64]) NanToZero() {
    for i := 0; i < m.Nrow; i++ {
        for j := 0; j < m.Ncol; j++ {

            if math.IsNaN(m.At(i, j)) {  // line 936, where the error is; ./slurp1.go:936:18: cannot use m.At(i, j) (value of type float64 constrained by Addable) as float64 value in argument to math.IsNaN

                m.Set(i, j, 0)
            }
        }
    }
}

go version go1.20.6 linux/amd64

Dan Kortschak

unread,
Sep 9, 2023, 7:04:53 PM9/9/23
to golan...@googlegroups.com
You will probably need to type assert.

Jason E. Aten

unread,
Sep 9, 2023, 7:24:54 PM9/9/23
to golang-nuts
Like how, specifically?

func (m *Matrix[float64]) NanToZero() {
    for i := 0; i < m.Nrow; i++ {
        for j := 0; j < m.Ncol; j++ {
            v := m.At(i, j).(float64)
            if math.IsNaN(v) {
                m.Set(i, j, 0)
            }
        }
    }
}
gives
./slurp1.go:944:9: invalid operation: cannot use type assertion on type parameter value m.At(i, j) (value of type float64 constrained by Addable)

Jason E. Aten

unread,
Sep 9, 2023, 7:31:25 PM9/9/23
to golang-nuts
I made a playground if anyone wants to play with it and figure out how to test their ideas.

Jakob Borg

unread,
Sep 9, 2023, 10:31:02 PM9/9/23
to Jason E. Aten, golang-nuts
Two minor issues; you can’t declare func (m *Matrix[float64]) NanToZero() because we don’t have specialisation, it needs to be func (m *Matrix[T]) NanToZero(), and you can’t have complex as one of the possible types because it’s impossible to convert a complex to a float.
-- 
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4f7e642b-ef44-4564-93e7-b2f7c10ffb6dn%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages