@Lilac@lemmygrad.ml
link
fedilink
6
edit-2
8 monatoj

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)

Examples

Haskell

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>>),

}

@OsrsNeedsF2P
link
fedilink
18 monatoj

Can you give examples? From the description, it seems like most languages (like Java) can store data in enums?

@acabjones@lemmygrad.ml
link
fedilink
48 monatoj

I think they mean that enum variants can contain fields, i.e. individual variants are themselves structs or tuple structs. AFAIK the closest thing to this in a C-like lang would be a tagged union type.

@lemtoman
creator
link
fedilink
38 monatoj

oh yes thats what i mean. Coded in rust, loved this feature, went back to python a bit and became sad that I couldnt do the same. Feels stupid that a variable can be different types depending on the situation, and having a dataclass where just one field is relevant seems too dumb

@northbound_goat@szmer.info
link
fedilink
8
edit-2
18 tagoj

deleted by creator

Ephera
link
fedilink
78 monatoj

Yeah, in language theory, this kind of thing is called an “Algebraic Data Type”: https://en.wikipedia.org/wiki/Algebraic_data_type

Rust Programming
!rust
Create a post
  • 0 users online
  • 1 user / day
  • 2 users / week
  • 12 users / month
  • 48 users / 6 months
  • 2.11K subscribers
  • 391 Posts
  • 431 Comments
  • Modlog