#Is there some workaround or package to allow generic methods?

9 messages · Page 1 of 1 (latest)

craggy sluice
#

A little bit of context. I'm trying to develop a parser combinators library for Go inspired in Nom (parser combinators library for Rust https://github.com/rust-bakery/nom).

Now I'm trying to implement a generic Map function for type Parser, in order to allow to user to map a parser result into another result. Here is the code that I have:


type Parser[O any] func(string) (string, O, error)

type MapFn[U any, K any] func(parsed U) (K, error)

func (p Parser[O]) Map(mapper MapFn[O, any]) Parser[any] {
    return func(s string) (string, any, error) {
        next, p1, err := p(s)

        if err != nil {
            return "", nil, err
        }

        p2, err := mapper(p1)

        if err != nil {
            return "", nil, err
        }

        return next, p2, nil
    }
}

Notice that the signature of the mapper (MapFn) takes two generic arguments, the original parsed result and the new mapped result type. The issue is that I cannot pass the new mapped result type to the Map method for the parser because it is generic and it is not allowed.

The easiest solution is just set the mapped result type as any, but I dont like the behaviour because I want to provide a "type safe" parsers; so use any will lead to cumbersome type assertions all the way.

So, Is there any way, package, workaround or pattern to allow generics in methods?

cobalt acorn
#

So, Is there any way, package, workaround or pattern to allow generics in methods?
writing a function instead of a method

craggy sluice
#

Sure, I know I can write a top level function, but I want to provide a clearer API in order to allow methods chaning in the Parser type

#

Using top level functions could lead to a lot of functions nesting, therefore a unclearer API IMO.

cobalt acorn
#

the only distinction between functions and methods is implicit chaining

#

I think you'll struggle to find anything better

#

generic methods don't work because the team doesn't know how to make them work, so there is no "actual" workaround, there are just other ways of accomplishing the same goal (not the same thing)

#

and if methods don't cut it, only functions remain

craggy sluice
#

Ummmm sure. I know the method generics feature is not available oficially, but I wanted to research about possibles workarounds over this issue because it is a very common feature in other languages.