Zulip Chat Archive

Stream: lean4

Topic: recursive functions and `variable`


James Sully (Jul 14 2024 at 17:27):

Is it expected that tri' doesn't compile?

def tri (n : Nat) : Nat :=
  match n with
  | 0 => 0
  | m + 1 => n + tri m

section
variable (n : Nat)

def tri' : Nat :=
  match n with
  | 0 => 0
  | m + 1 => n + tri' m

end

Kyle Miller (Jul 14 2024 at 17:36):

Yes, you can only do recursion on variables in the function's parameter list.

(A recent thread)

James Sully (Jul 14 2024 at 17:38):

Thanks! I guess my intuition that variable just adds to the parameter list of any definition that refers to it is subtly wrong

Kyle Miller (Jul 14 2024 at 17:48):

Not an explanation for why it works this way, but during elaboration these parameters are added before your tri' starts to be elaborated, and during elaboration a local function tri' is added (later, any calls to tri' will be "compiled out"). It makes some sense that this local tri' wouldn't be responsible for pre-existing variables.

James Sully (Jul 15 2024 at 02:31):

I can't quite follow this sorry

a local function tri' is added

  • what does "local" mean in this context?
  • added to what?
  • isn't tri' already there?

Kyle Miller (Jul 15 2024 at 17:40):

Added to the local context.

The tri' function doesn't exist globally until after the whole definition is elaborated and processed. Until then, there's a secret tri' function in the local context that you're referring to. (It's marked in such a way that you can't see it in the Infoview.)


Last updated: May 02 2025 at 03:31 UTC