rescript-lang/rescript-lang.org

Playground: Recursive tree with polymorphic variants blows up the stack

Closed this issue · 3 comments

To summarize the issue:

  • This yields a stack overflow

    let rec sum = x =>
      switch x {
      | #Leaf => 0
      | #Node(value, left, right) => value + left->sum + right->sum
      }
    
    let myTree = #Node(
      1,
      #Node(2, #Node(4, #Leaf, #Leaf), #Node(6, #Leaf, #Leaf)),
      #Node(3, #Node(5, #Leaf, #Leaf), #Node(7, #Leaf, #Leaf)),
    )
    
    let () = myTree->sum->Js.log
  • This one compiles

    type rec tree<'value> = [
      | #Leaf
      | #Node('value, tree<'value>, tree<'value>)
    ]
    
    let rec sum = (x: tree<'value>) =>
      switch x {
      | #Leaf => 0
      | #Node(value, left, right) => value + left->sum + right->sum
      }
    
    let myTree = #Node(
      1,
      #Node(2, #Node(4, #Leaf, #Leaf), #Node(6, #Leaf, #Leaf)),
      #Node(3, #Node(5, #Leaf, #Leaf), #Node(7, #Leaf, #Leaf)),
    )
    
    let () = myTree->sum->Js.log

Fixed now.