Last active
May 25, 2024 10:18
-
-
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/f6888d79804ba5b79a7ee0baf04a46737af84fb1
This file contains hidden or 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.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