How can I define algebraic data types in Python (2 or 3)?
Algebra of ADTs Product types and sum types are collectively called “algebraic” data types because they have algebraic properties similar to normal integers.
Just as algebra is fundamental to the whole of mathematics, algebraic data types (ADTs) are fundamental to many common functional programming languages. They're the primitives upon which all of our richer data structures are built, including everything from sets, maps, and queues, to bloom filters and neural networks.
In programming languages, it carries a similar meaning. An algebraic data type is a composite containing variables. a composite can further contain other types as variables as well. A recursive type can contain another instance of itself as a variable.
From HaskellWiki. This is a type where we specify the shape of each of the elements. Wikipedia has a thorough discussion. "Algebraic" refers to the property that an Algebraic Data Type is created by "algebraic" operations.
The typing
module provides Union
which, dissimilar to C, is a sum type. You'll need to use mypy to do static type checking, and there's a notable lack of pattern matching, but combined with tuples (product types), that's the two common algebraic types.
from dataclasses import dataclass from typing import Union @dataclass class Point: x: float y: float @dataclass class Circle: x: float y: float r: float @dataclass class Rectangle: x: float y: float w: float h: float Shape = Union[Point, Circle, Rectangle] def print_shape(shape: Shape): if isinstance(shape, Point): print(f"Point {shape.x} {shape.y}") elif isinstance(shape, Circle): print(f"Circle {shape.x} {shape.y} {shape.r}") elif isinstance(shape, Rectangle): print(f"Rectangle {shape.x} {shape.y} {shape.w} {shape.h}") print_shape(Point(1, 2)) print_shape(Circle(3, 5, 7)) print_shape(Rectangle(11, 13, 17, 19)) # print_shape(4) # mypy type error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With