4 ms·
How many languages have true sum or union types though? For example, in Haskell I can’t declare a function as (foo: (String | Int) -> Int) and then call (foo “b
by joppy 6y ago
How many languages have true sum or union types though? For example, in Haskell I can’t declare a function as (foo: (String | Int) -> Int) and then call (foo “bar”) or (foo 123), I need to create some kind of wrapper type (like Either) to contain the possibility of a String or Int.
If this were possible, there would not be such a proliferation of useless types throughout code, and code could be updated incrementally much more easily, since if I want to add the possibility of another type in a functions inputs, I don’t have to go and update every callsite.
- dddbbb 6y agoHaskell's Either is a 'true' sum type, it corresponds exactly to the way sums have been defined in the literature for decades, and also is the Curry-Howard representation of logical or. It necessarily must be inside a Either-like wrapper in order to be type safe, String and Int are ultimately different and so at some point we must discriminate between them. foo could call further functions with its argument inside itself accepting Either String Int, but eventually a destructor will be hit somewhere in the call stack. If String and Int do implement the same behaviour under some circumstance, then a typeclass should be used to define that behaviour. Then foo can have type (Bar baz) => baz -> Int, where String and Int have Bar instances.
- throwaway17_17 6y agoI’m curious, is the ‘true’ sum types, I mean where true is in quotes, based on the premise that lazy language can not have logically true sum types? Or is it in the quotes for some other reason?
- dddbbb 6y agoI was just responding to the parent comment's claim that Haskell's sum types are not true sum types.
- joppy 6y agoRight, so I must have used the wrong words “sum type” when I should have said “union type”, but I thought the intended meaning was clear. It doesn’t necessarily need to be inside an Either wrapper, that is an implementation detail, neither does there need to be a typeclass specifically defined for it. For example the new Dotty dialect of Scala has support for union types as I described them [1]. This is nice because it makes union of types an actual union operator, satisfying actual commutativity (A | B) = (B | A) and idempotence (A | A) = A, which Either does not without some extra explicit isomorphisms. [1]: https://dotty.epfl.ch/docs/reference/new-types/union-types.html https://dotty.epfl.ch/docs/reference/new-types/union-types.h...
- mplanchard 6y agoI agree with my sibling comment regarding Haskell, but your example essentially as written is possible in typescript. Python’s type system also allows it via the Union type, e.g. Union[str, int]