Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 3, 2026 20:22
Show Gist options
  • Select an option

  • Save dacr/16b8b9e2aadb93dfecee3e1988bcba1e to your computer and use it in GitHub Desktop.

Select an option

Save dacr/16b8b9e2aadb93dfecee3e1988bcba1e to your computer and use it in GitHub Desktop.
scala3 feature examples - tree as typed enums / published by https://github.com/dacr/code-examples-manager #84bba0cf-f501-4e42-80bd-6d05ebe1e8f8/fdaa4d44d9efb063eff20693820bac78cadb00b8
// summary : scala3 feature examples - tree as typed enums
// keywords : scala3, tutorial, @testable
// publish : gist
// authors : David Crosson
// license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
// id : 84bba0cf-f501-4e42-80bd-6d05ebe1e8f8
// created-on : 2021-03-23T17:18:13+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
//> using scala "3.4.2"
enum Tree[T]:
case Node(children: List[Tree[T]])
case Leaf(content: T)
def map[U](f: T => U): Tree[U] =
def convert(tree: Tree[T]): Tree[U] =
tree match
case Leaf(content) => Leaf(f(content))
case Node(children) => Node(children.map(convert))
convert(this)
@main def run():Unit =
import Tree.{Node,Leaf}
val tree = Node(Node(Leaf(1)::Leaf(2)::Nil)::Leaf(3)::Nil)
println(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment