5 ms·
Adding row polymorphism to Damas-Hindley-Milner
- rtpg 2y agoRow polymorphism is excellent. I was intro'd to it in Purescript, but I would like to say that Typescript gives you some things that rhyme with it through its combinations of records at the type level. Highly recommend people mess around with Purescript, you can feel how much pressure is relieved thanks to the row polymorphism tooling almost instantly. Truly, all we wanted as an industry is an easy way to bundle together various tags into our types, and row polymorphism gets you there. I think row polymorphism is a fairly straightforward thing compared to dependent types in general, but can let you crush a whole class of errors and pay almost nothing in terms of expression costs.
- enugu 2y agoSomtime ago, there was a debate on the ability of a static type system to model an 'open-world situation' where fields are added to records as model changes. (based on a post[1] which responded to a Rich Hickey talk). The crucial point was that structural typing on which row-polymorphism is based can model such open-world situations. Also, having such a system can free you from having overly nested types. It would be great if Purescript or row-polymorphism became more popular. [1] https://news.ycombinator.com/item?id=22090700 https://news.ycombinator.com/item?id=22090700
- arianvanp 2y agoThis is also why I like interfaces in Golang (as a Haskell developer). You simply define a slice of the world you want to see and anything that fits the box can be passed. It's just unfortunate golang interfaces dont support fields. Only methods. Typescript fares better with its interface type
- diggan 2y ago> It's just unfortunate golang interfaces dont support fields. Only methods. Why is that unfortunate? Usually when defining interfaces you care about the API surface without wanting to care about the internals of what will eventually implement that API. If you suddenly also spec fields with the interface, wouldn't be too easy to couple the internals to the API? I can't say I've programmed in Go too much, so maybe I'm missing something very obvious.
- n0w 2y agoThe API surface of some struct is determined by visibility, not by whether a member of the struct is a method or a field. I can't remember the specifics for why fields cannot be used within a Go interface but I do remember missing it a few times while writing Go code.
- fwip 2y agoI think the reasoning is that interfaces are implemented by a dynamic lookup. Part of Go's philosophy is that things that could be expensive (function calls) should be visually distinct from cheap things. Struct field access is cheap, hopping through a dynamic dispatch table is less cheap.
- rtpg 2y agoTook me a second to grok why the field access would require dynamic dispatch and it's because you have to deal with differing layout between structs.
- tmountain 2y agoPureScript is such a cool language. I wish it would get more traction, but it feels like it's competing in the same space as TypeScript, and TypeScript seems to solve the category of problems it addresses well enough for most people.
- runeks 2y ago> Highly recommend people mess around with Purescript, you can feel how much pressure is relieved thanks to the row polymorphism tooling almost instantly. > I think row polymorphism is a fairly straightforward thing compared to dependent types in general, but can let you crush a whole class of errors [...] Would you care to provide a few examples? I don't have experience with row polymorphism so I'm genuinely curious.
- tmountain 2y agogreet :: forall r. { name :: String | r } -> String greet person = "Hello, " <> person.name <> "!" greetWithAge :: forall r. { name :: String, age :: Int | r } -> String greetWithAge person = "Hello, " <> person.name <> "! You are " <> show person.age <> " years old." main :: Effect Unit main = do let person = { name: "Alice", age: 30, occupation: "Engineer" } -- greet can accept the person record even though it has more fields log (greet person) -- Output: "Hello, Alice!" -- greetWithAge can also accept the person record log (greetWithAge person)
- blue_pants 2y agoHow does it differ from structural typing in TypeScript though?
- tmountain 2y agoStructural typing relies on interface compatibility. Row polymorphism is a type-level feature in PureScript where record types are constructed with an explicit "row" of fields. In Practice, row polymorphism is more granular, allowing you to explicitly allow certain fields while tracking all other fields via a ("rest") type variable. Example: PureScript allows you to remove specific fields from a record type. This feature, is called record subtraction, and it allows more flexibility when transforming or narrowing down records. You can also apply exact field constraints; meaning, you can constrain records to have exactly the fields you specify. Lastly, PureScript allows you to abstract over rows using higher-kinded types. You can create polymorphic functions that accept any record with a flexible set of fields and can transform or manipulate those fields in various ways. This level of abstraction is not possible in TypeScript. These are just a few examples. In the most general sense, you can think of row polymorphism as a really robust tool that gives you a ton of flexibility regarding strictness and validation.
- weinzierl 2y ago"A record is an unordered collection of name to value mappings" If there is one thing that is for sure, it is that we have too many names for "collection of name to value mappings". In my book the term record is not what first comes to mind when thinking of unordered mappings. All of the usages of the word I can think of imply the possibility of access by name while retaining order. Sometimes this allows easy indexed access (database rows used to be called records) sometimes it doesn't (C structs which also used to be called record types).
- yazaddaruvala 2y agoI tend to agree with you. “Unordered” is very strange when clearly it is consistently “ordered” by some function(name, insertion_id) to facilitate low latency lookup. The iteration order seems arbitrary to a human, but that is exclusively because function(name, insertion_id) is not optimized for a human. It seems strange to call the collection “unordered” because of how it appears to a human.
- codeflo 2y agoUnordered simply means the order isn’t exposed, not that the bits have somehow literally fallen out of the computer and are scattered on the floor.
- taeric 2y agoI remember trying to explain to someone that Java's List type was ordered, where they thought ordered meant sorted. Turns out, language is tough.
- tialaramex 2y agoThis often comes up for map types. C++ std::map and Python OrderedDict are both "ordered" but in very different senses of that word. People who wanted one but got the other will most likely be unhappy. Both do always work for "golden test" inputs, which will satisfy the sort of person who writes unit tests after finishing the software by picking inputs and then mutating the checked outputs until the test passes...
- choeger 2y agoWell written! I wonder if there's a way to efficiently implement it without resorting to monomorphization? A function that's polymorphic can be transformed into a more primitive (say C or assembly) function that gets extra arguments that carry the "shape" of the type variable (think of sizes, pointers vs. values, etc.). Is there a similar strategy for these polymorphic records? I see two issues: 1. The offset of any particular field in the record is unknown at compile time 2. The size of the record itself is unknown at compile time (but this should be trivial as an extra argument.)
- pistoleer 2y agoSwift solves this by using witness tables. Witness table is a skeleton of the desired record shape. It records offsets of desired fields as found in the actual supplied record. Each function call the actual record is not passed, but its corresponding witness table instead. For instance, if the "prototype" of the argument is {int foo, float bar}, and I supply {int foo, int baz, float bar}, the table will be {foo: base+0 bytes, bar: base+8 bytes}.
- whatshisface 2y agoWhy doesn't it limit what it pushes on the stack to (foo,bar) instead of pushing (foo,baz,bar) along with an offset table? If the offset table is possible to construct at the callsite, compiling it into the call is also possible.
- Joker_vD 2y agoBecause the polymorphic function called may also need to pass the whole record it was given to some other polymorphic function a la "void storeInGlobalStorage(key: string, value: T)".
- sirwhinesalot 2y agoWhat pistoleer said basically. Lets say a function expects a 2D point and you want to pass in a rectangle struct (which has x and y plus more info). You'd do something like: void f({float x, float y} p); Becomes void f(void* p, size_t offsets[2]);
- marksabanal1 2y ago[dead]
- revskill 2y agoI do not think using theoretical concept would make the convoept easier to understand.
- jdmoreira 2y agoTotally unrelated to the topic but for my fellow Portuguese geeks, `Damas` is the same Damas that wrote the famous (or infamous) Portuguese C book. Blew my mind when I found out. https://www.wook.pt/livro/linguagem-c-luis-damas/99231 https://www.wook.pt/livro/linguagem-c-luis-damas/99231
- jjice 2y agoI'm not familiar with this book. Anything particular about it that would cause infamy?
- jdmoreira 2y agoat least in my circles it was considered way inferior to K&R. I read both and enjoyed both for totally different reasons. But some Portuguese might remember "Samad" a mock person used in some of the examples. Which of course is "Damas" spelled backwards. Relevant reddit comment: https://www.reddit.com/r/devpt/comments/qujip3/comment/hlmb9ym https://www.reddit.com/r/devpt/comments/qujip3/comment/hlmb9...
- kccqzy 2y agoIt's easy enough to add row polymorphism if there is no subtyping involved. It is an entirely different matter otherwise. For example if a function needs to take a record containing x as a field with type int, it should also accept a record with y as a field that it does not use. This is just like in traditional OOP if a function takes a base class pointer, you can pass a subclass class pointer instead, just that these subtyping relationships are not explicitly defined by users but inferred by the record contents. There is width subtyping and there is also depth subtyping. And we also need awareness of contravariance and covariance. I implemented the above as a toy type checker. I found the above combination of features too complicated and they end up being unintuitive for the user: the type errors are difficult to comprehend when type errors are found. My implementation is here: https://gist.github.com/kccqzy/d761b8adc840333af0303e1b822d769f https://gist.github.com/kccqzy/d761b8adc840333af0303e1b822d7... and I mostly followed the paper but I cannot guarantee there aren't bugs.
- calebh 2y agoFunctions that use a field called x but do not use a field called y can use the type {x=int, ... 'a}, right? The main difficulty I see with row polymorphism is with field shadowing. For example if you have a record with type {a=bool, x=int, c=unit}, then set the x field with type string instead, the new type should be {a=bool, x=string, c=unit}. I suppose if you only have syntax for creating a record with a literal, but do not have syntax for updating an existing record this is not a problem.
- kccqzy 2y agoI don't exactly understand your concern, but yes the type {x=int, ... 'a} is valid in a language with row polymorphism but without subtyping. If you do have subtyping, dealing with rest (or spread) is unnecessary. But if you remove subtyping, the unification algorithm isn't powerful enough on its own for many intuitive use cases. The easiest example is if a function takes a list of records all of which need an x field of type int, then you cannot pass it a list of records where all contain the x field of int but some also contain an irrelevant y field and others contain an irrelevant z field.
- abstractcontrol 2y agoI've thought about adding record row polymorphism to Spiral, but I am not familiar with it and couldn't figure out how to make it work well in the presence of generics.
- mrkeen 2y agoWhy is generics the tricky bit? Isn't that the bread-and-butter of this type system? You should just be able to substitute the term 'type variable' in the article for 'generics'.
- news_to_me 2y agoI'm loving this series, it's one of the best I've found for explaining HM typing in an approachable way. Looking forward to more!
- ggleason 2y agoIt would be extremely handy to have a document store / graph database which had row polymorphism. I started writing a prototype, but unfortunately never got there. I wonder if any such things already exist?