Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define algebraic data types in Python?

How can I define algebraic data types in Python (2 or 3)?

like image 955
user1234299 Avatar asked Apr 28 '13 01:04

user1234299


People also ask

Why are they called algebraic data types?

Algebra of ADTs Product types and sum types are collectively called “algebraic” data types because they have algebraic properties similar to normal integers.

Why are algebraic data types useful?

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.

What is algebraic data type in Java?

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.

What is algebraic data type in Haskell?

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.


1 Answers

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 
like image 190
Brent Avatar answered Sep 28 '22 00:09

Brent