prql icon indicating copy to clipboard operation
prql copied to clipboard

Weird currying behavior when returning a partially-applied function from another function

Open tantmd opened this issue 6 months ago • 1 comments

Currying a function across more than two lets gives the wrong result.

let f1 = func a b c -> a + b + c
let f2 = func a b -> f1 a b
let f3 = func a -> f2 a

from t | derive {
  y = (((f3 100) 20) 3),
  z = ((f2 100 20) 3),
}

I thought y and z should be equivalent but they aren't.

SELECT
  *,
  100 + 20 + 20 AS y,
  100 + 20 + 3  AS z
FROM t

y's c is 20 (the value of b) instead of 3.

The weird thing is it works for the 4th param.

let f1 = func a b c d -> a + b + c + d
let f2 = func a b -> f1 a b
let f3 = func a -> f2 a

from t | derive {
  y = (((f3 100) 20) 3 4),
  z = ((f2 100 20) 3 4),
}
SELECT
  *,
  100 + 20 + 20 + 4 AS y,
  100 + 20 + 3 + 4  AS z
FROM t

Looking at https://github.com/PRQL/prql/blob/4a9b9b667ffb45e2dd093bf70bf2bf4d6bb64ca4/prqlc/prqlc/src/semantic/resolver/functions.rs#L129. A function returning a partially-applied func seems to wrap it with a wrapper func and pass the remaining params through as _partial_i. Somehow f3's wrapper ends up shadowing f2's wrapper.

Guessing d is fine because d gets stored as _partial_1 while c is _partial_0, so d doesn't collide with f3's own _partial_0 from its partial application, but c does.

tantmd avatar Jun 04 '26 11:06 tantmd

Thanks for reporting this — and for the precise analysis, which was spot on. I reproduced it and confirmed the root cause: when a function returns a partially-applied function, the synthesized wrapper params were named by a per-materialization index (_partial_0, _partial_1, …), and because nested partial applications share the NS_PARAM namespace those names collided, so a reference resolved to the wrong binding.

I've opened #5979, which names the wrapper params from the resolver's global id generator so they're unique across materializations. Both the 3-param and 4-param reproductions now compile correctly. A maintainer will review it shortly.

prql-bot avatar Jun 04 '26 11:06 prql-bot