8 ms·
>I have never had a static type checker (regardless of how sophisticated it is) help me prevent anything more than an obvious error (which should be caught in t
by coldtea 6y ago
>I have never had a static type checker (regardless of how sophisticated it is) help me prevent anything more than an obvious error (which should be caught in testing anyway).
Obvious in retrospect is not the same as obvious. And such errors happen all the time, the same way without syntax checks typos happen all the time.
And "caught in testing" is 2 extra steps removed from caught immediately by the syntax checker running as you type or save: writing the tests and running the tests (and being thorough/lucky enough that this part of the code is covered in a test).
>But it is a stupid tool. It can only do so much. So, you now end up with artificial rules about how to satisfy this tool. And things that I know (and can justify or even formally prove for my use cases) are perfectly fine to do are suddenly not.
What thing that violates a type check would be "perfectly fine to do"?
Dynamic languages still have types (since you still need to pass around the right object with the right methods or fields to the call site, else it will raise an exception when you use a method/access a field/run a function on the wrong type).
def square(value):
return value*value
If value is not a numeric type, square is not going to be happy. And that's the case with most (all?) dynamic code.
What would be a counter-example that something not satisfying to a type checker would be "perfectly fine to do" in a dynamic language?
(I do accept that the static typed language is better to have generic and/or algebraic types, no make lots of invariants easier to express without ceremony).
- tom_ 6y agoSquaring is usually value*value. (a minor nit that shouldn't detract from your point - since in a dynamic language, you'd have potential type errors in addition to this sort of thing...)
- coldtea 6y ago>Squaring is usually valuevalue.* This version is optimized for the value of 2! (thanks, checked).
- deleted 6y ago[deleted]
- tines 6y agoIt depends on how sophisticated your type system is. For a pure HM type system, anything requiring rank-n types won't type check, but are theoretically sound in a type system that supports them.
- dack 6y ago> What thing that violates a type check would be "perfectly fine to do"? One good example is where you might treat records or "product types" as maps Let's say you want to write a function that can capitalize all the string fields in the object passed in. In a dynamic language, you could map over the values and apply capitalization trivially. It would be a one-liner. In a static language, you'd have a few options, but none are great: 1. You could use "reflection" or some dynamic feature to do this, but lose type-safety 2. You could make the function take in the union of all possible data types in your system, and then write a mapping function for each one. Then you're duplicating the logic N times, or at the least writing a lot of conversion boilerplate. 3. You could write two functions for each data type in your system to convert to a Map<String, Object> or some such and back, which lets you operate on the maps. Again, lots of boilerplate. Maybe you use code-generation for this? That would add complexity. In reality, you probably wouldn't even try to write such a function in a typed language because of how awkward it is. Maybe you'd just write specific translation functions for the records you know you happen to need. But I think that's what people mean when they say you're restricted by the type-system - because it can't verify those types of operations, you find workarounds when maybe that would have been the easiest way to implement something.
- adwn 6y agoAs a proponent of static typing (at least for larger programs): thank you, that was a very enlightening example for when dynamic typing can be superior to static typing.
- mssundaram 6y agoIt's pretty easy to do in Typescript and loses no type safety (without needing to assert or cast anything) type T = { [k: string]: number }; const t: T = { one: 1, two: 2, three: 3, }; const makeUpperCaseKeys = (v: T): T => { const keys = Object.keys(v); return keys.reduce((p, c) => { const key = c.charAt(0).toUpperCase() + c.slice(1); return { ...p, [key]: v[c] }; }, {}); }; console.log(makeUpperCaseKeys(t)); // { // One: 1, // Two: 2, // Three: 3 // }
- AQXt 6y ago> What thing that violates a type check would be "perfectly fine to do"? A typical example, in dynamic programming languages, is to treat numbers as strings and vice-versa; evaluate lists in boolean context; and so on. > If value is not a numeric type, square is not going to be happy. And that's the case with most (all?) dynamic code. Some programming languages will be glad to accept a string and treat it as a number -- see Duck Typing (https://en.wikipedia.org/wiki/Duck_typing https://en.wikipedia.org/wiki/Duck_typing).
- ArchieMaclean 6y agoCan you give an example of where doing this is useful?
- smabie 6y agothat sounds really awful, not "fine."
- adwn 6y ago> A typical example, in dynamic programming languages, is to treat numbers as strings and vice-versa That sounds great until it bites you in the ass really hard. In general, you want to catch unintended behavior as early as possible.
- astrange 6y agoYou want to, but they don’t. Those people just want to get stuff done, as opposed to a language like Haskell or stricter where you’ll never be able to get old code to run because newer compilers print errors that take a week to understand. There’s some old Yegge articles about this… PHP converting between strings and numbers is usually a mistake, but the one data structure doing everything (array and dict) is nice enough.
- bjoli 6y agoI don't think that is necessarily a dynamic language thing: that seems like your regular ad hoc polymorphism. Pascal allows it, IIIRC. So does C#. Being able to use a function on different kinds of arguments is orthogonal to the typing discussion. Scheme, for example, is dynamic yet very monomorphic. You have length (working only on lists), string-length, vector-length, bytevector-length etc.
- lisper 6y ago> If value is not a numeric type, square is not going to be happy. That is not necessarily true. In Common Lisp, with its generic-function based object system, you can extend the operation of any function at any time to cover new types. So, for example, one could define a method for SQUARE that operates on matrices. > What thing that violates a type check would be "perfectly fine to do"? (define (self-apply fn) (fn fn))
- adwn 6y ago> (define (self-apply fn) (fn fn)) Out of curiousity, what would be a practical application of this?
- lisper 6y agoSee: http://www.flownet.com/ron/lambda-calculus.html http://www.flownet.com/ron/lambda-calculus.html
- adwn 6y agoThat didn't answer my question. Let me rephrase it: When would you use (define (self-apply fn) (fn fn)) in an actual, real-life situation (outside of teaching lambda calculus)?
- kazinator 6y agoWithout additional arguments? Never. With additional arguments, it provides the function with access to itself. This could be used "under the hood" in an implementation to bootstrap the ability of named local functions to have themselves in scope, which is useful for writing ordinary recursion. Compilers and interpreters can achieve such a thing without any such jig like a Y combinator, because interpreters and compilers work with environments that are re-ified as objects. They are free to manipulate environments and evaluate/compile any piece of code in any environment they see fit.
- lisper 6y agoPersonally, I consider teaching the lambda calculus to be a real-life situation. Teaching the lambda calculus is no less real to me than any other part of my life. But OK, self-apply is not something you're likely to see in production code, and neither are Church numerals, which is where this problem shows up for real. But MAP, REDUCE, and APPLY are, and they all have the same problem as self-apply: their static types are infinite. This is a general problem with all static type systems. There are only two possibilities: either your type system is Turing complete or it is not. If it is not, then there are things that one might reasonably want to express that cannot be expressed, and if it is, then it is undecidable. Static typing is either constraining, or it is a Turing Tarpit (https://en.wikipedia.org/wiki/Turing_tarpit https://en.wikipedia.org/wiki/Turing_tarpit).
- kazinator 6y ago> And such errors happen all the time, the same way without syntax checks typos happen all the time. No they don't, because syntax is richly varied and nested, even in programs whose "type story" is bland. For instance, in some numerical program, there are lots of opportunities to make typos in the syntax, but the type of just about everything may be either float or else array of float (possiby string, if it has any error-handling code with messages, and bool if there are some logical operations). If you pass an array of float where a scalar float is expected, such that an error occurs, and if you don't catch this in your testing, it means you're not testing the code. Untested code is of a dubious status, even if it compiles with a static type system; testing is not negotiable. Note that functions like sin and cos have exactly the same type signature, yet it is disastrous if you mix them up. Static type checking doesn't help. Static type checking also doesn't help with mixed up variables: calling f(x, y) which should have been f(y, x) or something else, where x and y have the same type. In programs, chunks of code that are put together into the same module or function often work with multiple instances of the same type. It's more important not to mix up those instances, than to worry about type errors. The code could be wrong in all sorts of ways, yet statically check. That's where you need to step up the the argument into "True Scotsman's type systems territory": a sufficiently advanced type system can encode all those properties that prevent the mixups that the everyday type system doesn't. Yeah, well, nobody uses that; nobody understands it outside of a narrow slice of academia. Examples of the technique are such that encoding even a trivial property like "list is in sorted order" results in an a considerable increase of program complexity all concentrated in one place, and less easy to understand than a set of test cases against the obvious program. Yet, it doesn't eliminate the need for testing; nothing does. There can now be a bug in the way the desired property was encoded into the program. Perhaps the sorted property was correctly encoded, but it should have been descending order. The test case will catch it. When you have a language that is available at compile time, you can execute test cases as part of compilation. Test cases are therefore static checks. Anything happening at build time is a static check. Heck, how a git commit message is formatted is a static check, if a repository commit hook validates it.
- gugagore 6y ago> Note that functions like sin and cos have exactly the same type signature, yet it is disastrous if you mix them up. Static type checking doesn't help. I agree with you. I am hard-pressed to imagine types (where it's static analysis or anything at all) offering any help in catching inadvertent swaps of sin and cos. One thing that types could help with is avoiding confusion between e.g. radians and degrees. Even this I believe is quite a challenge, because the quintessential (in my opinion) example of static analysis and types as they arise in science and engineering, the SI units and dimensional analysis, take radians to be dimensionless and therefore do not distinguish the input and the output types of e.g. sin (Radians). I personally believe this problem is rectifiable beyond the SI type system (or who knows, within it), but not at no cost. I believe the choice to not distinguish the input and output types of e.g. sin (Radians) is rooted in many different practical considerations, and points to the difficulty of formalizing types in practice. > Test cases are therefore static checks. I don't agree with this unless you are talking about tests that perform some kind of symbolic execution / static analysis within them. What static analysis grants you is checking a "for all x" claim, without literally checking each x. You can argue that for any given static analysis system, the kinds of claims it lets you check are not that useful in practice, and I would agree in many situations. But having a finite number of test cases that tests some x is not the same as testing for all x.
- ywei3410 6y agoAn example: > y = [1] ++ [2] ;; Assume types List[Int], List[Int] > y[0] ;; This should return Union[Int, None] > y[0] + 3 ;; This should fail type-checking You /know/ the list isn't empty. Sure you can argue that /maybe/ we should be using NonEmptyList, but now imagine this code. > y = [1, 2] ;; NonEmptyList[Int] > y = (filter (lambda x: x % 2 == 1) y) ;; Has to return List[Int] > y[0] ;; Union[Int, None] Again, we hit into type issues.
- iso8859-1 6y agoThe type system is a proof system. In your examples, the types do not imply the invariants that you want. Does this mean that the type system is faulty? No! It just means that you need to e.g. get a more expressive type system, document code properly, use smart constructors. There are many tools. Nobody said you can trivially prove everything using type systems. So what are your examples showing? I see your code, but I don't know what you're actually trying to do. One interpretation could be, that you want to prove that for the naturals (excluding 0), up to and including 2, there is an odd number. Can one prove this using type systems? Definitely. If you read Software Foundations, you will know how.
- ywei3410 6y agoSure - but the point is that there are /diminishing returns/ on type-systems. The question is then, /where/ should one draw the line when trying to prove certain properties of code; which properties are worthwhile proving? Are you /seriously/ suggesting that one should use Agda or Coq for most code? EDIT. The original comment was suggesting as though dynamic and static type-systems are a dichotomy. I was pointing out that it is a sliding scale from nominally-typed ala Go, all the way to dependently-typed languages; and that's not even including model-checkers!
- seepel 6y ago> What thing that violates a type check would be "perfectly fine to do"? Here is an example limitation of typescript's type system that I routinely run into while developing real code [1]. I look at it like this. If you consider all possible programs, some are invalid, some are valid, and some are valid and useful. A type system's job is to reject as many invalid programs as possible while accepting as many valid programs as possible and trying to optimize for useful valid programs. Due to the halting problem this is impossible to do perfectly, so any given type system will likely accept some invalid programs and reject some useful valid programs. If the type system happens to reject your useful valid program, you'll likely have a bad day :) [1] https://www.typescriptlang.org/play?#code/PTAEHUFNQCwQwG7TgO1HADhgNgSwMZwAuuA9mkfEaACaRzYDOoA7rpaJOzJAE6gBlIgFc6KIs1L8AYnHzDsRAJ4A6AFC5xfAGZzoQ0ZHGgA3mtCcAtnFzYAXKEZFemgObnQrjHAdOXKdwBfNQ0tXl18aFl5RSVTD0hrW19nNw9GBjheJRT-IJCQUABJbVZo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7TgO...
- temp24582934 6y agoSometimes the type system is forcing you to think in terms of what it is that you are passing around. In this case, getEmails() isn't expecting a group of students or a group of faculty, but rather a group of people that can be emailed. You can introduce an interface of that type and have it inherited by both Student and Faculty and use that in the method for clarity and type-safety without over-relying on union types: https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=38&pc=30#code/JYOwLgpgTgZghgYwgAgArQM4HsTIN4BQyyEAtnMADYBcyGYUoA5gQL4EGiSyIoDKYAK4ATCOBIAPSCGEY0mHPiLImABzi16jEC3adw0eEmQAxRIMpgAnpOmz5UbLkLEMcSnChXNDZmw4wgiAIYMCKTBBgAKLkVBgAFExQWIKqtACCUFBwVgA86I44AHwAlErEUJGCULhJKaoAdOSq8fGqCiC0BU5lALxFyO2FIA1kFJQl-vrcRigAkjIQEhDCuQAqAy7IoKIStCCCpABG0MrAkKS0a1OBwaGKO0sA4smp60WJr2nImdl5GyUMlkcrkFrsVu9NspKkIaiovk04C14ucyAAabaLCR9KHECpVOF4TG7WiPCQY1GXbYXZDsYisSZ6UQIDyVZAIHD0OhCUTgDBAv65AQiMRgIoEZmslAckBcowWawCkFmBAKqziyWeaWcsDckV8gDyUBVaqVeW6xQ4EWisUoCXo+rAGEm1pi4wS8ssVhdkTdcXiDt5TqNJq9k30uxe9QDPNFzojzy+8U91kmZKjqRjjowIfMYaAA https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=38&pc=30...