this post was submitted on 01 Jun 2022
8 points (100.0% liked)

Rust Programming

8011 readers
1 users here now

founded 5 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] Lilac@lemmygrad.ml 6 points 2 years ago* (last edited 2 years ago)

Typed functional languages usually do, as mentioned by others. This is form of Algebraic Data Type called a Sum Type (as oppose to a Product type, which is basically a normal struct).

Here's some examples of creating a binary tree in different languages (also Lemmy's code formatter is terrible)

ExamplesHaskell

data Tree a = Empty | Leaf a | Node (Tree a) (Tree a)

F#

type Tree<'a> = Empty | Leaf of 'a | Node of (Tree<'a> * Tree<'a>)

Scala

sealed trait Tree[+A]

case class Empty[A]() extends Tree[A]

case class Leaf[A](a: A) extends Tree[A]

case class Node[A](left: Tree[A], right: Tree[A]) extends Tree[A]

Rust

enum Tree<T> {

​ Empty,

​ Leaf(T),

​ Node(Box<Tree<T>>, Box<Tree<T>>),

}