138 points · by marvinborner · 3y ago · 104 comments
With Liquid Haskell, the bound checks are moved from runtime to compile time, semi-automatically handled by SMT-solvers. Static types help programmers to write correct programs faster, and the programs also run faster.
As an aside, speeding up programs with static analysis (constrained dynamism) are also present in Mojo (a variant of Python) or Swift [2].
[1]: https://github.com/Gabriella439/slides/blob/main/liquidhaske... "Scrap your Bounds Checks with Liquid Haskell"
[2]: https://github.com/modularml/mojo/discussions/466 "Mojo and Dynamism"
You could theoretically remove all the unnecessary checks by hand, but it’s tricky.
Automatically removing bounds checking where safe seems like a good goal, but in all but the most trivial cases its quite complex for the compiler to decide what's safe.
Also if you are accessing a data structure out of bounds, that's a show stopping bug that shouldn't ever happen. That should be something that is prevented ahead of time, not recovered from. Tanking a program's performance to catch bugs in released programs is a bold strategy to begin with.
On a complicated single-process system (a monolith), that can be a big improvement. For distributed systems (microservices), there will still be plenty of runtime checks. That's what allows each service to have its own lifecycle.
I'm wondering what Elixir will do, given that Erlang servers divide up work into lots of independent, distributed components?
Libraries for TypeScript like Zod[0] allow you to define types and validate against them at runtime. For example: https://stackblitz.com/edit/typescript-pwzng4?file=index.ts
At work, we use this to validate API responses, local storage contents, or URL/router data. It solves the problem you described -- dirty data coming from outside of the type system.
This isn't a plug for Zod or TypeScript -- there are other similar libraries for TypeScript, and I would imagine other statically typed languages have something to fill this role.
[0]: https://zod.dev/
- why is there `safeParse`? Why is parsing not safe by default? Have an `unsafeParse` as an escape hatch, not the other way around.
- the imperative check for `success` seems unfortunate. Then again, I am familiar with pydantic from Python, which seems awfully similar to Zod, and there you'd get an Exception on failure which you'd have to catch. Some would call that uglier (I don't). Point being, I don't know of a better alternative, but sure hope native liquid/dependent types wouldn't suffer from this anymore
> the imperative check for `success` seems unfortunate.
Yes! But the cool thing is that `success` being `true` narrows the type and ensures that the `data` field is present. You cannot access `data` without checking for success
Here's another example showing those concepts: https://stackblitz.com/edit/typescript-wbuikz?file=index.ts
Result
.fromExecution(() => schema.parse(input))
.mapOk(parsed_input => /* */)
.mapError(parse_errors => /* */)
which is an alright way to deal with things IMO.I would hazard a guess that `parse` is a function introduced long ago, and `safeParse` came afterwards. (Safe as in "do not throw an exception")
`const result = schema.safeParse(val)` does not throw, and if `!result.success`, `result.error` contains a `ZodError` object with all the details. It's common to further transform this error object, perhaps to make it more human-readable or suitable for an API response.
Typically I find myself using `safeParse` far more than `parse`.
Glad to not have to write seemingly thousands of lines of interfaces and type guards any more.
[1] https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...
Validating on load is a form of runtime type checking. It’s not relying on a type assertion, which would allow the compiler to omit the type-check and the programmer to omit the error-handling when the check fails. Instead of preserving knowledge about the type constraints on some data, we prove the constraints again.
You can totally do that if you want and you fully trust that the thing that generated the data used the right types.
Similar to what you do every time you use a dynamic library.
...I'd read that article. Now I'm starting to think that I should write it.
What if instead of TS, you had plain JS as-is (no compiler needed!) then just add comment like:
/* x is an integer, x > 0 ... */
function add(x, y) { ...
Sorry the example ain't great but the point is that you can be precise with refinement types. I think refinement types (less all the mathy explanations) are more intuitive. They would be like assertions or C# code contracts. The content of those types would look "business-ey" rather than "category theory-ish".This link discusses, along with other usefulness, the use of dependent types for the likes of array bounds checking, creating "sorts" of numbers satisfying various predicates, and more interestingly the utility of combining Dependent Types with PURE Linear Types (as opposed to Affine Types a la Rust lol) ...
AFAIK, DML was originally intended as a gateway to constructing typed assembly (DARPA)
Having been a researcher in this field for, this quote from the original paper on 'Liquid Types' originally seemed suspect.... "a system that combines Hindley-Milner type inference with Predicate Abstraction to automatically infer dependent types precise enough to prove a variety of safety properties" .... type inference with dependent types is undecidable!? Then again, this is one of the primary focuses of ATS3, I digress...
This area of research is rich in pipe-dreams and cerebral investigation. From my biased opinion, ATS3 (the current version of the successor
3 of DML, being actively devloped by the PI Professor Hongwei Xi, is the only language in this space to be aimed at practical programming in industry... of course there is always haskell....)What I mean is that, TEMPLATES++ Linear Types + Dependent Types + Hindley Milner Type inference ....
At the end of the day, who doesn't love hyper efficient meta-programming magic?
Now, the Liquid Haskell type checker knows a lot about integers: it can deduce whether your invocation of x-y could give a negative result or not.
If it cannot result in a negative value (e.g. because y has a particular liquid type), the type checker will accept your program, and you'll be able to use the subtraction function as you normally would.
However, if your invocation of x-y could potentially result in a negative value (e.g. because the values of x,y are not sufficiently constrained), the type checker will reject your program, and tell you to do something else (e.g. add runtime checks that rule out a negative result before invoking the subtraction).
I think that's the main disadvantage of these types. It's now no longer a decidable system with (usually) easy to understand error messages. You're in the realm of formal verification and SMT solvers where the only error message is "didn't work; try something else".
Probably still good but I think it's important to be aware of the downsides.
As long as there's a good way to map from the real world into the liquid typed world, either by just telling the liquid typed world that this value can only be a positive integer, or by the liquid typed world having functions that ensure this at the boundary and return nice errors on runtime failure of this check, then it sounds really interesting.
For subtraction it becomes fallible. You get back an option, 5 - 4 = Some(1), 4 - 5 = None. (These are probably methods rather than infix operators, your language may vary.)
See for example the methods documented here: https://doc.rust-lang.org/stable/std/num/struct.NonZeroUsize...
As for it's utility, it enables certain optimizations and it can be a useful constraint. Eg for ensuring that you don't divide or multiply by zero.
That’s not true. 5 + (-5) is 0.
One usually doesn't program airplane control software. Some bugs are okay and speed of development and correctness is a trade-off.
Certainly, the language itself won't have liquid types in the compiler any time soon. But taking Ruby's Sorbet as inspiration, I wonder if you could annotate Java classes with semantic rules and do some simple verifications as a post-compilation step?
There's too much bad code out there that can't just be replaced. Tools to help make it better would be a huge boon.
[0] https://www.thestrangeloop.com/2018/contracts-for-getting-mo...
Personally I find refinement types more promising than dependent types, but time will tell.
LSPs are a sort of middle ground where I derive a lot of the value from, and even weak type systems really help the analysis of the LSP. They make me immensely more productive. I've been writing a lot of TypeScript lately, and I may not have taken the plunge to the frontend if LSPs hadn't made it dramatically easier. So in that case the impact on my productivity is +100%.
Especially when dealing with someone else's code, it can be a ceremonial roadblock for moving data around that could easily be processed without issue but artificial constraints in order to service an orthodoxy have been erected to make things needlessly more brittle.
In the name of reducing bugs, it in practice can often impose workarounds that increase the chance the confusion and more bugs.
This isn't always the case but most of the time things are built in incompetent hands (including my own). Accommodating for this reality is probably the better move. Imposition of absolutist rules doesn't improve the behavior of incompetency, it just makes it more subversive and the defects it creates more insidious
I try not to think of it as whining, I try to think of it as the type checker helpfully pointing out, "hey, you haven't done your due diligence here." I ran into this advice when learning Rust and it made it much more pleasant. In the same way that you might chase a series of failing tests to finish a task, you can chase a series of type warnings. I have them integrated into my editor, so usually the "series" is length 1 because I'm knocking them out as they arise.
The projects I've worked with that were previously untyped (Python SaaS backends), I never actually ran the type checker on the entire source code. But if I had a megabyte of type errors that weren't really going to provide value to the business, yeah that would feel like a waste of time. Unless we were having serious quality issues and it was between annotating the entire codebase and rewriting it from scratch, I'd leave well enough alone - it's a tool, not a religion. But the new code I'm checking in, that's getting annotated for sure.
I don't really see types as arbitrary absolutist rules. They're the semantics of the language, they're the rules you're following whether you have a typechecker or not. And if you violate them you're gunnuh get bugs and crashes regardless. I too am a flawed human who frequently makes mistakes, and I like having them caught immediately, before I've even checked my code in.
There's type narrowing, warnings for not awaiting Awaitables, generics, protocols/interfaces, even whole function signatures can be lifted into the type system (ParamSpec). Dictionaries can be turned into typed versions as well, which is quite powerful.
By default, it's weaker, as it's optional. Rust's isn't optional. But start a greenfield project with type annotations and you won't be disappointed, I hope. Features like ADTs will still be absent, but I feel that's an orthogonal issue to type safety etc.
"Python wasn't weak, I was" is an accurate call out, I have abandoned complex annotations in Python before because there was a bunch of cruft involved and the documentation wasn't always as straightforward as I'd have liked.
The lack of ADTs (and thus a Result type) combined with the lack of exceptions as part of the function signature (like Java) make it really difficult to develop a reliable application. Maybe that's not quite a type safety issue, but it's a safety issue for sure.
Digging in, it looks like people are working around this by returning exceptions, which is very clever and I hadn't thought of it before.
you either create a complex program, with simple language constructs, or a simple program with complex language constructs
if you use only the simplest types, your program will be very complex, if you put all the complexity in types, your type system will be very complex
you need to balance things
i think OOP is the extreme where all the complexity is in the Object system (or types system)
functional programming with complex types, i think give a nicer balance, where some logic goes into the program flow and some goes into types
anyway balance is everything, keep things balanced , dont lean too much into any direction
Languages and libraries that are well designed and compose better end up being great at taming complexity. Functional languages are made to compose better, but their popularity is a hint that they are not that simple to use effectively.
do you have any in mind ?
I often think about a blend of functional and OO as 'protocol graphs' but it's a faint idea for now
As a library developer I spend substantially more time on making the types right than the actual implementation. It can be brutal at times.
I guess you can complain that Typescript forces you to spend time making sure your code meets a minimal bar of correctness...