83 points · by keymone · 9y ago · 114 comments
I feel the opposite way. I find a dynamic approach useful in some places, but in most places I miss having static typing to help catch errors faster and give my IDE better auto-completions and make exploring new APIs faster without constantly needing to look things up. And rather than small intricate algorithms, I find the most important place for static typing to be when making big refactorings that span the whole codebase. I think my ideal language would have static typing by default but you could disable it in places.
The water is nice, you should jump on in.
It seems to me, that types are useful for useful for expressing the boundaries of components, but they seem rather awkward constructs to be wrestled with to express the invariants and predicates about the state of the program that I invariably end up using in my head to insure that my code is correct.
For example, one might simply want to insure that three variables, say x, y and z, satisfy the relation (x <= y && y <= z) while inside a loop. The x, y and z might be integers or account-numbers or zip-codes or anything else with the <= predicate.
What I want is not to twist the type system around to say that just while in this loop the type guarantees that (x <= y && y <= z). What I want in a programming language is to be able to express this as a claim I'm making about the program at this point and to have help from an interactive theorem prover that it is so. I'd expect some sort of dialog with my tooling that would point out where I needed to make changes to guarentee this or to indicate that it is a claim stronger than needed for the program to run correctly (and satisfy it's specifications). Type systems just don't seem very natural for this; I would think we would use something like Dijkstra's weakest-preconditions or temporal logic over program states.
I really am asking for help in understanding where research on programming correctness is currently headed. (You don't have to explain it like I'm a fifth grader, I've been programming for 50 years, many in grad school.)
--------------------------------
(quote from someone named Racketnoob) “I have the strange feeling that types hamper a programmer’s creativity.”
The above sentence is a compact summary of the reluctance that programmers often feel in migrating to statically typed languages — that they are losing something, a degree of freedom that the writer identifies as hampering creativity.
Is this true? I will argue, to a degree — yes. A type checker for a functional language is in essence, an inference engine; that is to say, it is the machine embodiment of some formal system of proof. What we know, and have known since Godel’s incompleteness proof, is that the human ability to recognize truth transcends our ability to capture it formally. In computing terms our ability to recognize something as correct predates and can transcend our attempt to formalise the logic of our program. Type checkers are not smarter than human programmers, they are simply faster and more reliable, and our willingness to be subjugated to them arises from a motivation to ensure our programs work.
That said, not all type checkers are equal. The more rudimentary and limited our formal system, the more we may have to compromise on our natural coding impulses. A powerful type system and inference engine can mitigate the constraints placed on what Racketnoob terms our creativity. At the same time a sophisticated system makes more demands of the programmer in terms of understanding. The invitation of adding types was thus taken up by myself, and the journey to making this program type secure in Shen emphasizes the conclusion in this
I wonder if it might be possible to feed predicates from clojure.spec to the inference engine/type checker from the Shen java port to gain static type checking. I wish I had more time to work on this kind of fundamental research, but alas I'm merely a working programmer schlepping data to and fro.
imo without those the argument (to anyone outside Clojure world) appears to be "lets just use open maps for everything", which is not really conveying the larger point - that one can have reasonable structure and description/enforcement of that structure using predicate language, which to some extent can be applied during compile time and enables static analysis tools. it's a compromise between rigidity of haskelly type system and the wild-west of tossing open maps around.
If instead it was merely a form of static analysis, then it could easily be seen as something that can be added. Which, in many languages, it can be. The forms of analysis the advanced tools can give for C codebases is quite impressive. All without having to rewrite the system with more precise types.
Similarly with LISP. It is widely lauded as a very popular dynamic language. However, there is nothing stopping you from statically analyzing it. Obviously some practices make this more difficult, but sometimes just having an escape hatch for the developer is enough. Just as obviously, these practices that truly make it hard to analyze statically aren't used that often. That is, a decent sized program will almost certainly use the features in a few spots. But only a few and the majority of the code can still be analyzed easily statically.
Sometimes I wonder why there aren't more 'empirically' typed languages, i.e., you write a function and some unit tests that exercise it and from that the compiler can determine what are the actual types and values the function sees for every variable.
As an easy example, if you are looking for functions that can return a Foo, autocomplete does little to help you know that you have to call .convertToFoo() on any of the baz instances in scope. There is already more than just basic type mapping going on. (To that end, a graph traversal assuming shortest path from symbols in scope to the desired shape works. So it is doable, of course.)
To your question of "empirically typed", that is close to some of the stuff that more advanced tools can do. I liked showing folks that Coverity wouldn't just tell you that you forgot to check for null, but would show you how the null would get there from the call patterns. Quite impressive.
Well, sure there is. Someone has to decide it's worthwhile to build it, then they have to build it, and polish it to a point where it's usable which generally means a community has to form around that tool.
Years of work.
Doesn't surprise me that people think it's more worthwhile to just use a statically-typed language.
But, and this is my point, this was effort that had to happen in creating the static languages, too. Just now we locked out the benefits to existing problems to problems that are rewritten in the new languages. Contrast this with hardening existing codebases by running enhanced tooling against them.
This also ignores some of the analysis for lisp languages. I know typed racket comes up every week for this topic. It didn't invent type checking for lisp, either.
Dynamically typed languages, on the other hand, don't really have that much more research that can even be done with them. Can't do any more research on the type system because there isn't much of one. Really the only thing you can do is introduce language features that are difficult to type in a static system, but at that point you're just giving more theory CS phd students targets of things to find a novel way to type.
That being said, the problem with static type systems is that there is a lot of details that you need to figure out to A) be able to use it and B) be able to avoid the edge cases. You'll eventually need to learn about type theory ... which isn't just one thing. Agda and Idris have incompatible definitions of equality and that has an impact. Are your dependent types intensional or extensional? It matters. And that's just the theory side. Two different type systems with the same theory might have different implementation details that impact the programmer. Are you using ML? Is that an applicative functor or a generative functor? Hey, you're using first class modules, cool. Btw you can't use that with applicative functors, don't ask why it has something to do with complicated type theory stuff that took people years to figure out. Using haskell? Is it GHC or is it some alternative ... because that impacts some type class definitions that are possible.
Eventually the static types are going to win because we'll slowly figure out how to type everything (well, nearly everything) and we'll slowly figure out how to package that power in a way that everybody can understand.
However, in the mean time there is a very real cost to having to learn any given static type system that doesn't exist if you live in a dynamically typed system. Additionally, if you do understand some type theory you can bring over the lessons learned to your dynamic system. You won't get type checks at compile time, but you will get a more disciplined way to produce code.
[1] - http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=029...
> the problem with static type systems is that there is a lot of details that you need to figure out to A) be able to use it and B) be able to avoid the edge cases. You'll eventually need to learn about type theory ... which isn't just one thing. Agda and Idris have incompatible definitions of equality and that has an impact. Are your dependent types intensional or extensional? It matters. And that's just the theory side. Two different type systems with the same theory might have different implementation details that impact the programmer. Are you using ML? Is that an applicative functor or a generative functor? Hey, you're using first class modules, cool. Btw you can't use that with applicative functors, don't ask why it has something to do with complicated type theory stuff that took people years to figure out.
that in itself is one of the best arguments for strong dynamic systems with small set of ground types - if before solving your problem you have to solve the problem of how to type your problem and before that you have to learn man-years worth of category theory.. no thanks.
In these instances you might as well create a dynamically typed system and see what happens when it meets real life. Yeah it might fail, but the static version was going to fail too. You can save time by not having to worry about what the "proper" type is.
The other side of this is: What do we really want our types to do for us? This isn't always the same thing for everyone. I've created DSLs in a dynamic system that failed in weird places and when I tracked down the reason it was because I was using two functions together that did not agree on the "type" they were passing between themselves. In this instance, type theory wasn't going to help solve my problem, but a quick "typecheck" of the code would have pointed me in the right direction to find a silly mistake. On the other hand, sometimes you can use types to solve your problem. I know it's a bit cliche, but rust is a good example of this. If you want to avoid GC but still want high level programming features and no memory corruption then linear types is one way to achieve that.
No you don't. Most of the most prolific Haskell programmers (Don Stewart, Neil Mitchell, Lennart Augustsson, probably SPJ himself) would tell you they don't know any category theory.
In the same way that static systems are moving toward something that looks like dynamic typing with static safety, so are dynamic systens via gradual typing and optional static analysis tools. I don't think static or dynamic as we know it now are going to win, the dominant model of the future may well be one where broad inference allows statically verifying most constructs without type annotations, and languages support either allowing and disallowing constructs that aren't verifiable (and maybe even support disabling static analysis entirely, though people who use that option for anything but prototyping will be mocked as unprofessional.)
I do agree that "eventually statically checked specifications are going to win", but I'm not sold that those specifications will take the form of (something easily recognizable as) a type theory. (However, neither outcome would surprise me).
> You'll eventually need to learn about type theory ... which isn't just one thing.
I'd say that most Java developers are comfortable with its type system, including the parametric polymorphism that it supports, and most of them probably don't know much about type theory. The same can probably be said of C#.
> we'll slowly figure out how to package that power in a way that everybody can understand.
I think we're already there. Java's generics appeared in 2005, and while there probably was some cultural shock in the Java community in the years that followed, it's safe to say that most of this community can claim to have a reasonable understand of generics in general. The addition of C# and its type system helped disseminate this knowledge further.
What would it mean for a StaticScript program to typecheck? It doesn't guarantee it will have no type errors. The model you typecheck against may be very different from the runtime truth. Browsers are different and provide different features, and will change after your program is compiled.
Static type checking has a fundamental limitation: it happens too early. The more divergence between the static model and runtime truth, the less useful static typing is. This is a fundamental limitation, a place where static types can never supplant dynamic ones.
In any case, your example is one in which static languages are no worse than dynamic ones, so it is not one which prevents static languages from displacing dynamic of they are otherwise superior.
1. When accesses are resolved dynamically, the failure mode is better controlled, e.g. exception instead of buffer overflow.
2. The failure is deferred to the point of execution (instead of e.g. load time). It is easy to omit features that depend on missing runtime support, just arrange for that code to not be executed.
3. Dynamic types allow you to interrogate which interfaces are supported, via reflection.
We see all of this at work in (good) web sites. They gracefully degrade, they can dynamically choose implementations based on what the browser supports, and failures are JS exceptions instead of aborts.
> In practice, of course, that's a bigger problem with interpreted than compiled languages
Why does interpreted vs compiled matter? IMO the key distinction is dynamic linking vs static linking. When you link against code compiled after yours, the less assurance static types give, and the more important dynamic types become.
> static languages are no worse than dynamic ones
The proper comparison is between languages with dynamic types and languages without. TypeScript has both static and dynamic types. If it had no dynamic types, it would not be a viable JS replacement.
> This is just a guess, but at the time he wrote Clojure, those type systems most likely were Java-style (Java, C++, C#) and Haskell
SML and OCaml pre-date some of the languages in that list, and certainly pre-date clojure.
The "positional semantics" section -- and that whole class of arguments -- never made any sense to me. All languages have hash maps, so this is about program design rather than language design. Or perhaps, at most, an argument for having nice syntactic sugar for hash maps. In any case, I'm not sure what this has to do with fundamental language design issues. The "can Haskell..." stuff has a similar smell to it. The answer is always "yes, Haskell (and everyone else) have hash maps and HOFs."
At best, it's an argument that those languages should provide a bit of extra syntax around the "everything is a map" programming style. Which, I won't disagree with :)
> In the kinds of systems Rich is talking about, any data could possibly be missing... At the limit, you would need to make everything Maybe
Which is why ML-family languages have both exceptions and algebraic data types.
The discussion of abstraction is just confusing. The author seems to define "abstraction" as "literally any list of information". And I guess it's true that pathologically bad abstractions do exist, but... what point is being made here? I don't get it.
The "screwing around in the type system syndrome" thing actually makes sense, but you can see the same thing in dynamic languages (e.g., with meta-object protocols or macros). There's something more fundamental here, and it's more about human psychology than language design.
I have to agree with keymone, though, that the really interesting thing about clojure is not its design but rather clojure.spec. Sure, you lose a lot of static guarantees, and along with them some of the maintainability/correctness that come along with statically typed languages. But perhaps recovering static checks, and tooling based on static checks, is best done on a library-by-library basis via compositional specification checkers specialized to the particular library. Rather than by a single general-purpose type theory that's rich enough for the "real problems in the messy world" type of programming. And the article kinda starts hinting at this toward the end. But I think keymone really hits the nail on the head when it comes to what you should take away from learning/working in clojure.
+1 !
If necessary you don't need to use and ADT+pattern matching on JSON. You just work with the hashmap directly.
But the code that results is very simple while remaining strongly typed.
It ends up being not that different in style from something like hpricot in ruby.
type Object = HashMap Text Value
which is A JSON "object" (key/value map).The keys of the hashmap are Text and the leaves are "Value" which contain more JSON
here are different well-formed json values that both resolve to the same type, A.Object (either you get a parse error String for not-well-formed json, or an A.Object)
>>> A.eitherDecode "{ \"name\": \"Joe\", \"age\": 12 }" :: Either String A.Object
Right (fromList [("age",Number 12.0),("name",String "Joe")])
>>> A.eitherDecode "{ \"name\": \"Joe\", \"age\": {\"foo\": \"12\"} }" :: Either String A.Object
Right (fromList [("age",Object (fromList [("foo",String "12")])),("name",String "Joe")])
Then you can access values in the HashMap by key just like a hashmap in any other language.Or, as noted by chowells, you can use lens-aeson which can be thought of as a DSL to perform queries in a dynamic fashion:
retrieve value of "foo" in "age"
>>> s = "{ \"name\": \"Joe\", \"age\": {\"foo\": \"12\"} }" :: String
>>> s ^? key "age" . key "foo"
Just (String "12")It's not different for that type. The point of using a statically typed language is you can give static types to other entities in your program!
> The tools Haskell gives you are great at some things, but dealing with arbitrarily nested ADTs is not one of them.
There's nothing more natural in Haskell than recursion and processing of ADTs. There are dozens incredibly well-research patterns for processing just about anything under the sun.
> What we wound up doing was nesting pattern matching to get at the value we wanted. The deeper the JSON nesting, the deeper our pattern matching.
In my experience that works great for moderately complicated and ugly JSON messages. Tried that in Haskell, OCaml and Rust. Rust was most clunky due to the way things are represented in serde (I expect that's more performant though) but still worked nicely.
Alternatively, lenses would allow for incredibly easy access to just about anywhere in any JSON document. Want to hit multiple nested targets in weird locations? No problem!
> But imagine if more and more of your code is dealing with JSON. It would be nice if there were some easier way.
Sadly the author skipped explaining that mythical "easier way".
MLs are widely cited as some of the best languages for implementing compilers in, and large chunks of a compiler consist of transforming various ASTs. An AST being a particularly complex recursive ADT, it seems strange to claim that's a weak point of statically-typed languages.
However, I was parsing some ugly format that doesn't deserialize cleanly:
match v.as_slice() {
&[Value::String(ref s), Value::Object(ref o)]
if s.as_str() == "i" => {
// more code here and still need to unpack x and y from o
}
to parse something like `["i", {"x": ..., "y": ...}]`. In Haskell you could do: case j of
Array [String "i", Object o] | Just x <- HashMap.lookup "x" o, Just y <- HashMap.lookup "y" o ->
// code goes here, can refer to x and yRich's biggest complaint is that our tools should be a la carte not forced down our throat at every turn. Type verification (static or not) should be a tool, not a religion. (In this way, Rich renders the perennial static vs. dynamic debate stupid: it's a false dichotomy that most statically typed languages needlessly force us into.)
In Rich's talk, the bigger target of his attack is ADTs -- that is, processing information in any way that doesn't make properties first-class. (It's easy to mix up his argument against ADTs and static types, probably because ADTs are kind of like the go-to idioms for people programming in statically typed languages.)
I think one of Rich's one-trick ponies (i.e., one of his goals) is to remove the impedance between thinking and coding. We humans don't naturally think in terms of ADTs (e.g., when you open a dictionary, you see vocabulary/words, not categorical types/ADTs.) Computers only ask us to be precise and ADTs are unnecessary to achieve precision -- properties ("words") capture all of the precision needed to solve our information-processing problems.
All Rich is doing is trying to remove that impedance between thinking and coding.
Static types are also unnatural and unnecessary to the precise expression/coding of solutions to our "situated" programming problems. I don't think any static typing enthusiast would disagree. What the static typer would say, though, is that they've done something clever: they're adding the extra impedance of type verification to achieve a higher level of problem-solving throughput. (Because their static types reduce other impedances: bugs, refactoring ease, etc.)
Are the static typers right? Rich seems to imply no. (Because even though he says typing should be a la carte, you can clearly see in the talk that he has his predilection.) The fight here is usually left to our intuitions and habit, but my guess is that someone smarter than me could model this programmer-productivity problem as an optimization formula, showing how over time software-construction slows down due to certain constant impedances like juggling static types and certain accumulative impedances like coupling and code quality in a large code base.
My guess is that this formula would show that in low-quality code bases with lots of coupling, the static typing tax would win. But that in higher-quality codebases the static typing tax wouldn't pay for itself. This jives with my instincts of course but you also find that the better programmers (the ones that know how not to couple shit) favor dynamic typing while those that regardless of experience haven't learned how to keep coupling at bay prefer static types.
Haha, wow. That is some serious reaching there. And let it be known, I'm not referring to myself as some great programmer, because I don't think I am.
1. You imply static typing is a tax rather than something that reduces cognitive overhead as time goes on.
This point is very debatable.
2. You imply that 'clearly, anyone who doesn't favor dynamic programming is a lower quality programmer who doesn't know how to keep coupling at bay'.
That's pretty ridiculous, if you weren't cackling with anticipation at the responses to your flamebait then I have to assume you're serious, and you've already drunk the koolaid.
(add [x y] (+ x y))
(add [^Integer x ^Integer y] (+ x y))
Both of these are equally precise (in terms of telling the computer what to do). The latter one prima facie requires more thinking, more typing, and more work. (Side note: the sky is blue.)2:
I don't mean to make such the broad generalization that you're jumping to here. What I mean to say is that static typing in the traditional mode (non-a la carte, applied everywhere, w/ all of the typical idioms of ADTs, pattern matching, etc etc) may help in cases where your code is heavily coupled, complex etc, but I think that its a needless impedance in higher-quality codebases.
There are many languages in which the `+` operator can be applied to types that are not integers.
In a static type system with inference, both examples would just be
(add [x y] (+ x y))
as the `+` operator is enough to infer that the parameters need to be a number. So your point is true for some statically typed languages, but certainly not all (ML-likes, Haskell-likes, and others with strong type inference).2:
In my experience, ADTs (and pattern matching in particular) make coding problems much easier to solve (and the code itself considerably simpler) than the alternatives in many languages. For example, I'm writing a compiler in Go, for fun, and a lot of tasks would be far easier and more concise to express with ADTs/pattern matching. Another example is working with pattern matching in Elixir/Erlang, especially with binary data, which is beyond easy to express a parser for with pattern matching. Elixir and Erlang are dynamically typed, and have gradual typing via Dialyzer (though it's rather different from clojure.spec I believe), but pattern matching is pattern matching, and it's indispensable in my opinion.
Using something dynamic, like Lisp/Javascript/Ruby/Etc. would make it much more difficult to navigate the code for something like a non-trivial compiler (in my experience), and more difficult to reason about how it will execute. The other thing I don't see mentioned very often is that if the compiler can't reason well about your code, then it can't optimize it very well. Even with a JIT, you are paying a performance cost that is non-trivial, unless you happen to be using a language with a particularly good JIT, performing tasks that the JIT is good at optimizing at runtime. For a lot of tasks, this overhead doesn't matter, but I would rather lose some flexibility to be able to use the same language for a broader array of tasks.
Recently I was taking a stab at translating some code for an Earley parser from some dynamic languages (Javascript and Python) to Go, again for fun, and in both cases found it was impossible to do so because of the way the dynamic features of the language were abused - basically I would have to throw out everything and write it from scratch. The code was hard to reason about, because while reading it, you think you are working with values of a certain type in one function, but the same value somewhere else is getting treated like a different type. You basically have to execute the code to see what it does. Such flexibility can make for more concise code, but when the code _isn't_ concise, it can make it incredibly difficult to untangle. That's just my experience though. I'm an Elixir/Erlang programmer during the day, so I'm not anti dynamic languages by any means, but I have definitely found it easier to build certain types of applications in statically typed languages.
let plus x y = x + y
This is a statically typed function. If you are going to talk about static typing, learn about type inference and avoid making yourself ridiculous.Also, the fact that types are dynamic doesn't mean you don't have to think about them, you still have either type errors (like in most lisps) or implicit coercions (like in JS, you probably don't want that).
I don't agree with this.
Static typing is the stronger sense (than C or C++) is mostly represented by:
- ML
- oCalm/F#
- Haskell
- ADA
Coupling is not idiomatic on them. This is mixed with the functional + inmutable aspect (not much on ADA, but as someone that used to work on pascal is not the mess of the C family...), but certainly coupling is WAY higer on JS/Python/Ruby.
By TONS. And certainly less skilled developers code on them. By orders of magnitude. Haskell scare people. Python not.
And that is despite the fact I totally love python. I don't say python is bad. Skilled developers totally love pytyhon too.
---
What I think is better to say, assuming always a capable programmer:
- A good programmer can program good.
- A good programmer prefer to use better tools, if posible
- A good programmer wanna do things faster (also, to make programs faster, but let's focus only in his own productivity)
But exist two ways! to do this:
- A good programmer love dynamic typing because he can manipulate the program in do things past what is obvious. He can do complex stuff easy.
But it miss the simple stuff
OR
- A good programmer love static typing because he can avoid to worry about trivial things, like always check if something is null, look at the documentation/code to see what is returning, etc. So he can focus in the complex stuff. However, do certains kinds of complex stuff make him wish to use something else.
However, I bet MILLON TIMES that truly everyone wanna:
- To have both static types for the code that is in the past/stable and dynamic for now. Static when things are settle and dynamic when not. And move between boths with fluidity so he can construct things on runtime and then get back on tracks for the stuff that not need to change!
I'd make that same bet, too.