Zulip Chat Archive

Stream: lean4

Topic: Define type of trees of fixed depth


Vasilii Nesterov (Jul 22 2024 at 09:22):

Hi there! I'm trying to define an inductive type of trees with fixed depth like this:

inductive MyTree :   Type where
| leaf : MyTree 0
| node {n : } : List (MyTree n)  MyTree (n + 1)

Lean complains about:

(kernel) invalid nested inductive datatype 'List', nested inductive datatypes parameters cannot contain local variables.

I also feel that there's something wrong because I want to use the inductive structure of while defining MyTree, and I don't know how to acheive this. Are there good ways to overcome this problem?

Daniel Weber (Jul 22 2024 at 09:53):

You could define general trees then take a subtype

Daniel Weber (Jul 22 2024 at 09:54):

inductive MyTree :   Type where
| leaf : MyTree 0
| node {n c : } : (Fin c  MyTree n)  MyTree (n + 1)

this also works

Thomas Murrills (Jul 22 2024 at 22:56):

You could also define your own List specialized to MyTree:

mutual

  inductive MyTree :   Type where
  | leaf : MyTree 0
  | node {n : } : MyForest n  MyTree (n + 1)

  inductive MyForest :   Type where
  | nil {n : } : MyForest n
  | cons {n : } : MyTree n  MyForest n  MyForest n

end

Though I suspect that if you want them to actually have depth n in a nontrivial sense, you might want a "list that always has at least one element", i.e.

  inductive MyForest :   Type where
  | single {n : } : MyTree n  MyForest n
  | cons {n : } : MyTree n  MyForest n  MyForest n

instead? (Alternatively, that requirement could be bundled into the .node constructor for MyTree by giving it a MyTree n argument in addition to the MyForest n argument)

Joachim Breitner (Jul 23 2024 at 06:41):

Your first attempt fails due to https://github.com/leanprover/lean4/issues/1964. @Arthur Adjedj has a solution on a branch, but it's not clear when and if that will make it into lean. If this is blocking you, feel free to describe your use case on the issue.


Last updated: May 02 2025 at 03:31 UTC