v icon indicating copy to clipboard operation
v copied to clipboard

Higher order functions with `&int` params get changed to `int` params at compile time

Open memoriesadrift opened this issue 2 years ago • 1 comments

Describe the bug

Higher order functions defined with &int params get passed / evaluated as int.

Expected Behavior

Indirect and direct function calls should behave the same, see reproduction steps.

Current Behavior

:!v run test.v
test.v:21:13: error: cannot use `fn (&int, &int) int` as `fn (int, int) int` in argument 2 to `indirect`
   19 |
   20 | mut b := [5,1,3,4,2]
   21 | indirect(b, f)
      |             ^
   22 | println(b)
   23 |
Details: expected argument 1 to be NOT a pointer, but the passed argument 1 is a pointer

Reproduction Steps

pub fn indirect(array []int, callback fn (&int, &int) int) {
  mut test := array.clone()
  test.sort_with_compare(callback)
}

f := fn (a &int, b &int) int {
  if *a < *b {
    return 1
  }
  if *a > *b {
    return -1
  }
  return 0
}

mut a := [5, 1, 3, 4, 2]
a.sort_with_compare(f)
println(a)

mut b := [5, 1, 3, 4, 2]
indirect(b, f)
println(b)

Possible Solution

No response

Additional Information/Context

No response

V version

V 0.3.3 7a31831, timestamp: 2023-03-04 21:42:37 +0100

Environment details (OS name and version, etc.)

OS: macos, macOS, 13.2.1, 22D68 Processor: 8 cpus, 64bit, little endian, Apple M1 CC version: Apple clang version 14.0.0 (clang-1400.0.29.202)

memoriesadrift avatar Mar 04 '23 21:03 memoriesadrift

Using function types seems to mitigate the function parameter types error 😕

type Fnp = fn (&int, &int) int

// pub fn indirect(array []int, callback fn (&int, &int) int) {
pub fn indirect(array []int, callback Fnp) {
	mut test := array.clone()
	test.sort_with_compare(callback)
}

f := fn (a &int, b &int) int {
	if *a < *b {
		return 1
	}
	if *a > *b {
		return -1
	}
	return 0
}

mut a := [5, 1, 3, 4, 2]
a.sort_with_compare(f)
println(a)

mut b := [5, 1, 3, 4, 2]
indirect(b, f)
println(b)
└> ~/Develop/vlang/v/v run "/Users/devros/code/vlang/w3jan/tst.v"
[5, 4, 3, 2, 1]
[5, 1, 3, 4, 2]

DevrosTheOne avatar Mar 05 '23 03:03 DevrosTheOne

The code compiles successfully and the output can be seen on the playground https://play.vlang.io/p/430165e6c7

Delta456 avatar Aug 03 '24 19:08 Delta456