vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.76k stars 2.16k forks source link

cannot return a function from a generic function #22011

Open Cergoo opened 2 months ago

Cergoo commented 2 months ago

Describe the bug


module parselona

pub struct ParserResult[O] {
    i []u8
    o O
}

type TParser[O] = fn([]u8) !ParserResult[O]
type TF[O] = fn([]u8) O 

fn take_part(count int) TParser[[]u8] {
    return fn [count] (i []u8) !ParserResult[[]u8] {
        if i.len<count { return error('error len: ${i}') }
        return ParserResult[[]u8] {
            i: i[count..],
            o: i[..count],
        }
    }
}

fn fmap<O>(p TParser[[]u8], f TF[O]) TParser[O] {
    return fn [p, f] <O>(i []u8) !ParserResult[O] {
        r:=p(i)!
        return ParserResult[O]{i:r.i, o:f<O>(r.o)}
    }
}

fn test_1() {
  input := '10_ttt_uuuu_qqq_'.bytes()

  f := ParserResult[int] {
    i: [u8(1),u8(2)]
    o: 1
  }

  nnn:=take_part(2)  
  println('hhhhh ${nnn(input)!}')
  fnf := fn(i[]u8) int { return 1 }
  n := fmap[int](nnn, fnf)

  f1 := n(input) or { println('errr') return }
 println('hhhhh ${f1}')

  assert ['nn'] == ['ttt_', 'uuuu_', 'qqq_'] 

}

Reproduction Steps

v test parselona_test.v

Expected Behavior

complit test

Current Behavior

FAIL     0.000 ms /home/prof/projects/v/parselona/src/parselona_test.v
 compilation failed:
parselona.v:49:9: error: cannot use `fn ([]u8) !parselona.ParserResult[O]` as type `fn ([]u8) !parselona.ParserResult[int]` in return argument
   47 | 
   48 | fn fmap<O>(p TParser[[]u8], f TF[O]) TParser[O] {
   49 |     return fn [p, f] <O>(i []u8) !ParserResult[O] {
      |            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   50 |         r:=p(i)!
   51 |         return ParserResult[O]{i:r.i, o:f<O>(r.o)}

Possible Solution

for some reason type parametr not expansion

Additional Information/Context

No response

V version

V 0.4.7 3ca5bc3

Environment details (OS name and version, etc.)

Linux Mint 22

[!NOTE] You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote. Other reactions and those to comments will not be taken into account.

Cergoo commented 2 months ago

see https://github.com/vlang/v/issues/13253

medvednikov commented 2 months ago

A simple reproducible example:

fn closure<T>(input T) fn () []T {
 return fn [input] <T>() []T {
  return [input, input]
 }
}

fn main() {
 f := closure(123)
 println(f())
}
medvednikov commented 2 months ago

It's related to @yuyi98's fix https://github.com/vlang/v/pull/15529