242 points · by jrsinclair · 7y ago · 112 comments
> Arrays, Objects, Maps, WeakMaps, and Sets are all algebraic data types
This isn't really true on a couple levels. Algebraic Data Types are described through a small set of composition (data) or decomposition (codata) operations. Arrays, Maps, and Objects might be explainable in this way (though, really, we'd just be modeling them with ADTs). WeakMaps and Sets really cross the line though. WeakMaps, by their nature, need to appeal to something much more than just ADTs and Sets require "quotienting" to unify sets which contain the same elements in various ways. You can build the "raw stuff" from ADTs, but you won't have something that really behaves much like these types at all until you add in something extra.The emphasis on sum types is huge, but it leaves out something critical: "JavaScript doesn’t have a lot of built-in features for sum types" is true of user-defined sum types (and related to it just not having types all together), but it has great support for a few special sum types: integers, booleans, characters! These sum types are important to talk about because it helps make clear that we already work with sum types all the time! Our basis for distinction and choice is built atop them in any language.
Finally, while products and sums get you some wonderful modeling capabilities, the place where Algebraic Data Types really shine is when you add two further capabilities: function types (exponentials) and recursion (fixpoint, which doesn't really map to high school algebra). Those are clearly built into JavaScript as well and would be great to discuss as well.
- User defined Sum types - Pattern matching on these Sum types in switch statements - Blocks and things-that-are-currently-statements becoming expressions that evaluate to a value.
If it got those, then it would pretty close to the perfect dynamic language for me.
The real benefit of pattern matching is the compiler checking at least that you have valid cases, and ideally that you haven't missed any cases.
switch (mylist) {
| [“”, _, “”] => x
| _ => y
}
Moreover, pattern matching usually involves pulling information out of the object at the same time. In the above example, maybe you want to do something with the middle element: switch (mylist) {
| [“”, middle, “”] => middle ++ “!”
| [“foo”, x] => String.reverse(x)
| _ => “never mind”
}
All of this would be possible to do with a series of if conditions, but significantly harder to read and implement correctly.The power of pattern matching grows clearer as more complex data and rules are introduced. For example, it works just as well with nested lists:
switch (mylist) {
| [outer, [middle, [inner]]] => outer ++ middle ++ inner ++ “!”
| _ => “never mind”
}
While having a type system is helpful in all of the ways a type system is generally helpful, there’s nothing about this code which wouldn’t also be handy in a dynamic language like JavaScript. For further evidence of this see Erlang and Elixir, dynamic languages which make heavy use of pattern matching.(Code typed on my iPhone so forgive the dopey examples)
Scala example:
myList match {
case Nil => 0
case first :: Nil => first * 3
case first :: second :: Nil => first - second
case first :: second :: rest => first * second + sum(rest)
}Natural = Zero | Successor(Natural)
Bool = True | False
The mapping from Natural to Integer is standard.
You can rote learn that, but the reason why it's intuitive to call them sum types is because you're adding the number of possible values. With product types, you multiply the number of possible values that the type represents. Consider these types:
-- 1 + 1 = 2 possible values
data Bool = True | False
-- 1 + 1 * a = 1 + a possible values
data Maybe a = Nothing | Just a
-- 1 * a + 1 * b = a + b possible values
data Either a b = Left a | Right b
-- 1 * a * b possible values
data Pair a b = Pair a b
-- 1 * a * b * c possible values
data Triple a b c = Triple a b c
`Maybe Bool` would have 1 + 2 = 3 possible values.`Either (Pair Bool Bool) (Maybe Bool)` would have (2 * 2) + (1 + 2) = 7 possible values.
Integers would be defined as:
data Int = ... | -2 | -1 | 0 | 1 | 2 | ...
if they were finite, but since they're not, they'd have to be defined recursively with something like: data PositiveInteger = One | Succ PositiveInteger
data Integer = Zero | NonZero Bool PositiveInteger
where the Bool represents the sign.Since 2 * x is the same as x + x, we can also define it as:
data Integer = Zero | NonZero (Either PositiveInteger PositiveInteger)
where Left of Either would represent negative integers, and Right of Either would represent positive integers.For a product type with no “or”, consider the JavaScript object {}. We see these as “atomic”.
Before defining the integers, one must define the natural numbers. Natural numbers are defined as an inductive type, which is a little different from an ordinary sum type:
data Nat = Z | Suc Nat
Here is another way of defining them. Start by removing the self-reference: data NatF a = Z | Suc a
Notice that NatF is the same thing as the Maybe/Option type, AKA 1+a, AKA the sum of the unit type and a.Given a "fix" type:
data Fix f = MkFix (f (Fix f))
the definition of the natural numbers would be: type Nat = Fix NatF
An "F-algebra" is a way of defining some algebraic structure or data type as a map from a "sum of products" to the type. More precisely, an F-algebra consists of an "object" (type) A and a map F(A) -> A. For the natural numbers, the F is NatF and the map would be a function mkNat : NatF Nat -> Nat, AKA mkNat : (Maybe Nat) -> Nat or mkNat : (1 + Nat) -> Nat.Related links:
- https://ncatlab.org/nlab/show/inductive+type
- https://ncatlab.org/nlab/show/natural+numbers+object
- https://ncatlab.org/nlab/show/initial+algebra+of+an+endofunc...
- https://en.wikipedia.org/wiki/F-algebra
---
One way of defining the integers is as the product of the natural numbers with themselves, or Nat * Nat, equipped with an equivalence relation ~ where
(a, b) ~ (c, d) := a + d = b + c
(a, b) can be understood as a - b. Of course, a - b = c - d <-> a + d = b + c.
Another way of defining the integers is as:
data Int = Neg Nat | Zero | Pos Nat
where 0 = Zero, -1 = Neg Z, and +1 = Pos Z.---
Booleans can be defined as 1 + 1. Left () = True and Right () = False, or vice versa.
data Nat = Z | Suc Nat
^ What does this crazy construction mean syntactically?It looks like it is trying to do something like (from your link) Coq's
Inductive nat : Type :=
| zero : nat
| succ : nat -> nat.
But obviously defining natural numbers in terms of Z/the integers doesn't work because I could then call -1 a natural number.Instead, you can extend algebraic data types to combinatorial species, which do allow exactly the kind of quotienting you speak of. While they're unexplored in programming, they are believed to be programmable similarly to ADTs.
https://repository.upenn.edu/cgi/viewcontent.cgi?article=177...
I must take issue with the "objects are products" characterization you implied. Structures are products; objects need existential types: http://www.cis.upenn.edu/~bcpierce/papers/compobj.ps
I never thought I would understand point set topology, but for a few years I really did. (That was quite a few years ago, and since I haven't practiced... Well, it atrophied. Still remember my favorite proof, though! I also remember what a nightmare proof Stone–Weierstrass was :) ... amazing, but still a nightmare.)
Every time that functional programming patterns get discussed, though, there is a mad rush by functional programmers to impress upon everyone just how complicated they are.
It is the same impulse that keeps the mathematical entries in Wikipedia accurate but utterly worthless for most people.
Huh? They're part of Pascal (known as variant records) and plenty of other languages besides. It's mostly C that lacks them, and even then you're just expected to implement them yourself, for maximum efficiency.
"plenty of other languages besides" doesn't matter if those languages aren't being used in practice.
Let me list off the top 10 languages (incl markup) from the most recent Stack Overflow survey, specifically the Professional Developers tab. https://insights.stackoverflow.com/survey/2019#technology-_-...
* JavaScript
* HTML/CSS
* SQL
* Python
* Java
* Bash/Shell/PowerShell
* C#
* PHP
* TypeScript
* C++
You can argue about the demographics of Stack Overflow or the bias in users who actually respond on these surveys or a million other things. But based on job postings I've seen in the last several years, I'd wager this list is pretty accurate.
It sounds like GP is saying they had never used of those languages beforehand. I'm not sure why would be so surprising given that it doesn't accompany any other information like "and I had used 20 other languages before it".
Just enable -Wincomplete-patterns or -Wall!
For example if you write this in Haskell
data PrimaryColor = Red | Green | Blue
colorToInt Red = 1
colorToInt Green = 2
colorToInt Blue = 3
it is closed because future code can't add more alternatives. Instead you must simulate it using type classes, with a wildly different syntax, and (some would say) a hack. Or define a different sum type that wraps the above.OCaml on the other hand supports the above perfectly with a slightly different syntax, but it also supports polymorphic variants (not to be confused with a Haskell sum type that's polymorphic because of a type variable like Maybe) which are lighter weight. For example you can write a function that takes different "constructors" without necessarily giving a definition for the type or listing all alternatives:
let color_to_int = function
| `Red -> 1 | `Green -> 2 | `Blue -> 3
Notice I never defined any type for the three colors! If you wish, you can mention the type: [< `Red | `Green | `Blue ]
or give it an alias to make it look more normal. But you can add (with some limitations) or remove more things to this variant later on.To me, though, the most intuitive way of understanding this is to think of the first as nominal typing, whereas the second is structural typing.
(Now with optional laziness.)
Here the Rust book mentions it:
> async bodies and other futures are lazy: they do nothing until they are run.
https://rust-lang.github.io/async-book/03_async_await/01_cha...
I just read it, and thought it was odd. I don't understand how Rust's async relates to a laziness as in Haskell's laziness.
In particular, I wonder about their characterization of sum types. I had to search to make sure, but they never say the word "union". This is curious, because they do understand "tag" and "tagged" as words used to describe sum-type behavior, and because the classic way to explain sum types to "imperative" C programmers is as "tagged unions", or union types with a tag value that explains which of the union's constructors is present. C or Java programmers would instead prefer an analogy with subtyping, which the article proceeds to use, but by overlooking the tagged-union analogy, the author is actually missing out on both a useful analogy for reaching out to imperative programmers, and also how low-level implementations of functional programming languages usually implement sum types.
Pattern-matching is probably the killer part of ADTs, but only two paragraphs were spent upon the concept. Worse, it's implied that pattern-matching is tied deeply both to ADTs and to functional programming, when it occurs outside of those contexts. Languages like Python 3, Ruby, Racket, and Swift fall outside of the traditional "functional programming" traditions but still have interesting pattern-matching abilities.
The author still doesn't know Haskell. Want an effectful loop? Control.Monad.Loops [0] contains many prebuilt loops, and they're written in standard Haskell. The ST monad [1] provides imperative variables and mutation. So does IO [2], if one insists on avoiding GHC for some reason. I agree that it's good to learn an ML, and Haskell is a fine choice, but the author needs to realize how drenched in Haskell memes they currently are, and to either learn more of Haskell itself, or to take a break from it for a while.
[0] https://hackage.haskell.org/package/monad-loops
[1] https://wiki.haskell.org/Monad/ST
[2] https://hackage.haskell.org/package/base/docs/Data-IORef.htm...
(a, (b, c)) = foo()
(fst, *middle, last) = foo()
which is nice but i wouldn't really call it pattern matching because i can't do something like match xs:
when (): ...
when (x, *rest): ...
i.e. do different things based on the shape of the data.Perhaps one day we will be able to have similar discussions about sum types without constant interjections by functional programmers.
A class in Java for example is a product type. As it describes a group of fields and their types. Same for a struct in C++.
Where I disagree with the article is that JavaScript does not have product types, because you do not have a definition of such a group of values in advance. A JS object does not list what values it groups and what type they each will have. A JS class comes closer in listing what values it will group, but not their types. Also, product types must be closed, and a JS class defines an open group, at runtime the object could group more then what it specified, unless explicitly frozen. You could say a frozen class defines a product of types where all types are the Object type and thus can be of any value, but that's a stretch, because product types are only as useful as they define a constrained product of possible values for the type.
A sum type is just a known list of possible types a value can take. That's the one people aren't as familiar with as most popular languages don't have a construct like it. It let's you say, this variable can be a String or an Int, but not both.
Often people say product type is AND while sum type is XOR. This variable contains a String AND an Int. They will both be there. So it contains both. That's a product type. This variable can contain a String XOR an Int, they can't be both contained, it is only one or the other. That's a sum type.
You can think in Java that all types are a sum type, they are either null or of their defined type. But null isn't a real type, more that it is an allowable value of all types. So it's a bit of a stretch.
Like the article said, best way to mimic them in popular languages is by extending an abstract class. Each type the variable can be will be a child of the parent. Thus a variable of type parent can be one and only one of its children. It's not full featured, you can't make existing types extend from the parent, so you can't arbitrarily define sum types using any available type. You also often can't list what are all the possible types of parent, depending on the reflection capabilities, knowing what all extend a type isn't always feasible. Also, the static type checkers don't consider these like sum types, so it won't tell you that you forgot to handle cases where parent is of one of its child type. Etc.
There is a lot of scala reference material regarding ADTs
> Keep persevering. Don’t give up. If you find that a bunch of blog posts don’t explain things in a way that makes sense, skip them. Keep looking until you find some well-written ones. The same goes for courses and tutorials. Everyone comes from different backgrounds. What makes sense for someone else might not work for you. And that’s OK.
I feel like this is advice everyone should hear, especially junior or mid level developers
Something I've found confusing with algeabric data types is the fact that they are not mathematical concepts. They originate as a programming construct and were invented as part of a programming language. They were then given a name that makes it sounds mathematical, but it was just an attempt at giving some kind of metaphorical meaning to them. Same as if I name a search engine Odin, because Odin was the God of wisdom. But if you thought it had anything to do with Norse mythology you'd similarly get confused.
People tried to find correspondence for them with mathematical theories. Thus, in Set theory they could correspond to Disjoint Unions of Cartesian Products. Or in category theory, they could correspond to Coproducts of products.
I guess you could say they came out of type theory, but I'm not sure of the history here fully. Did the extensions to simply typed Lambda calculus first came out of the theory or did it retroactively built a theory from the programming construct?
At any rate, my point is, these mathematical correspondence are very confusing. And I think it's wrong to try and understand these things from the mathematical angle unless you're a mathematician trained in one of the corresponding mathematical theories.
As such I think the article does a good job.
1. https://codewords.recurse.com/issues/three/algebra-and-calcu... 2. http://www.math.lsa.umich.edu/~ablass/7trees.pdf
I'm sure there's quite many things in programming language where you can use such correspondence to your advantage, not just ADTs. But we don't teach it starting from the mathematical correspondence and then back.
To put it more simply, most programming isn't thought by first teaching learners about theoretical computer science. Generally it happens either in parallel or you learn the theory after the fact. But for some reason, when it comes to functional programming it seems most teachers want to start with teaching you the theory.
And my above point is that, even historically, it is not always true that theory came first. Often times, the construct were invented and used practically from finding solutions to concrete problems, and later a theory around it was developed. In the case of ADTs, I'm not 100% sure which came first, but I know they were first implemented in the programming language Hope. Not sure if the theory was there prior or not.
https://math.stackexchange.com/questions/50375/whats-the-mea...
It is not that there are no mathematical correspondence, but ADTs are not constructs of any mathematical theories. There's no ADT in set theory. There's no ADT in category theory. The only place you might find them is in type theory, but that's unclear to me if that is the theory that defined them, or simply the theory used to define them mathematically after their invention in computer science. And like Gilles answer suggests, ADTs brings some concepts that complicates the mathematical formalism for them.
This is why the whole sum type and product type thing is loosy washy. You can say Java classes are product types, but they are not quite like Haskell's product types, etc. They aren't an implementation of a very well defined mathematical theory. Unlike say how Java and Haskell both have support for set theory and algebra built in.
I wouldn't say that this is true. Category theory has a definition of product of objects, sum/coproduct of objects, terminal object (unit type), and initial object (empty type). There is a correspondence between type and category theory where a certain type theory is the internal language of a certain category: https://ncatlab.org/nlab/show/computational+trinitarianism
Product: https://ncatlab.org/nlab/show/cartesian+product
Coproduct: https://ncatlab.org/nlab/show/coproduct
Terminal object: https://ncatlab.org/nlab/show/terminal+object
Initial object: https://ncatlab.org/nlab/show/initial+object