Last active
April 2, 2023 10:11
-
-
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/6c8b0126038d97bb63e6681f93a3e2f343cac6a4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : scala3 feature examples - tree as typed enums | |
// keywords : scala3, tutorial, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// 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.1.1" | |
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