358 points · by miqkt · 9y ago · 212 comments
+1
One approach that occurred to me was to use Haskell and Hackage for prototyping a design and then a Rust implementation for production.
It also reminds me of this from several years ago: GHC honcho Simon-Peyton Jones saying the next Haskell will be strict, but still pure with effects only via monads. [1], [2].
Following on and presumably related to that PureScript is strict. [3]
[1] https://news.ycombinator.com/item?id=1924094
[2] http://www.cs.nott.ac.uk/%7Egmh/appsem-slides/peytonjones.pp... (PowerPoint) Slide 40
[3] https://github.com/purescript/purescript/wiki/Differences-fr...
SPJ made a great lecture about this. It is very easy to follow and a fun insight into the academic history of modern functional languages https://www.youtube.com/watch?v=re96UgMk6GQ
Idris is strict too, but optional laziness is built into the compiler with the use of a special-cased Lazy wrapper of the form
data Lazy a = Delay a
This is kind of the opposite of strictness annotations (bang-patterns) from Haskell, except one doesn't need to pattern-match on Delay or use it to wrap arguments to functions expecting Lazy values. The Idris compiler can do something like "laziness analysis" (admittedly trivial in comparison to GHC's strictness analyser) to introduce and eliminate Delay constructors automatically. The laziness information is carried around in the types: force : Lazy a -> a
force a = a
https://github.com/idris-lang/Idris-dev/wiki/Unofficial-FAQ#...(purescript-lazy is also a thing, but I think it's not as seamless because of the "no compiler magic" position.)
In any case, what about -XStrict? I've never used it (or -XStrictData either), but isn't it a solution to the laziness problem, albeit a nuke-ish one at that?
And while we're thinking ahead, let's talk about the project to get linear types (something similar to Rust lifetimes, but weaker) into GHC :)
Why weaker? My understanding is that linear types provide a stronger guarantee than Rust's affine types: linear types guarantee that a value is used once, while affine types only guarantee that a value is used no more than once.
I think all he meant that strictness was an interesting paradigm that would differentiate a language enough to justify its existence alongside Haskell.
>Following on and presumably related to that PureScript is strict
Partly also to distinguish from GHCJS. Laziness in a strict language is really hard and PureScript generates semi-readable JavaScript.
If it's really a struggle for some reason, you can always take the nuclear option and enable strict mode on your code.
Haskell is very good for writing extremely fast code that's also extremely composable, which most languages (even Rust, to a substantial degree) really struggle with. Haskell's pure non-strict semantics and support for fusion/rewrite systems means that you can write complex operations on vectors, byte arrays, text, etc. that span multiple modules but get compiled down to extremely tight in-place assembly code. Another way of looking at it is that the economies of scale for Haskell are very different. There's a higher up-front cost because you have to learn about how strictness works, but as a consequence you can write vastly more complicated programs that are, say, 80% as fast as hand-optimized C for only 10% of the effort of hand-optimized C.
Computer Language Benchmarks of GHC versus C don't seem to be close to matching your 80% as fast claim [1]. Also, the 10% of the effort of hand-optimized C bit - seem to recall there was a caveat - "if you happen to Don Stewart" [2].
The following is just my vague, uninformed impression, but Haskell and Go seem to be opposite ends of a spectrum, with Rust somewhere in between:
Haskell: good for expert individuals and small teams. The language is highly sophisticated and the compiler is rather slow. At heart, it's a research language, so the direction might not always suit production use. If you contract out to a Haskell development shop, who do you turn to with your Haskell code-base if things don't work out?
Go: designed by Google for their use-case - large teams of commodity programmers. It's very quick to onboard programmers - they can be productive and non-dangerous quickly. The language is very simple and the compiler is very quick - which is again good for scaling large teams.
[1] https://benchmarksgame.alioth.debian.org/u64q/compare.php?la...
[2] https://donsbot.wordpress.com/2008/05/06/write-haskell-as-fa...
Your comparison between Haskell and Go is about market size, not language design. I suspect you would have a similarly hard time finding Rust devs as Haskell devs (i.e. mildly less convenient than a popular language like Python or Go).
That's a really bad benchmark. The power of Haskell is not that it's fast for generating the Mandelbrot set, it's that it allows you to things you couldn't do in any other language while still being fast enough to write e.g. compilers (Idris) or web services (Yesod).
Heh
Other real world programs have a strict "always push things into the world, react to inputs" cycle that Haskell has trouble supporting.
Well, yeah, Rust has manual memory management. Of course you don't get space leaks.
Anyways, Rust's laziness is not on par with Haskell. Iterators are great but it's not at all the same as e.g. GHC's lazy IO.
I wouldn't call Rust's memory management "manual". It's the only language I know of that I'd describe as having automatic memory management without garbage collection.
> Anyways, Rust's laziness is not on par with Haskell. Iterators are great but it's not at all the same as e.g. GHC's lazy IO.
Iterators, futures, and macros (for creating new language constructs) tend to provide the laziness I want. Beyond that, I've tended to find laziness as much a source of bugs as features. (Speaking from a perspective of having written and maintained large programs in Haskell, and in Rust.)
Trying to compete with Rust or C++ performance in Haskell is certainly frustrating to reason about :)
TL;DR: "fast" isn't well-defined, and for a lot (or even most) applications "fast" is about latency, not throughput, and Erlang is "faster" in that sense.
[1] https://making.pusher.com/latency-working-set-ghc-gc-pick-tw...
[2] they eventually abandoned Haskell for Go https://making.pusher.com/golangs-real-time-gc-in-theory-and...
The other big part of this is that it can make stream fusion predictable. Currently haskell programs can become 100x slower or faster after some innocuous change, so linear types will make it a lot easier to write fast haskell in general.
Obviousness is hard to pin down. What may be completely obscure to a Haskell beginner is obvious to a veteran. Is it really fair to count people's strict-language preconceptions against Haskell? I don't know.
GHC provides a wealth of profiling tools that an expert Haskell user can employ to find space leaks. Heck, experts generally know where to look (excessive use of lists, spine-nonstrict data structures) so that the profiling tools become a last resort.
for (int i = 0; i < N; i++) {
a[i] = 2*b[i];
}
for (int i = 0; i < N; i++) {
c[i] = 2*d[i];
}
into for (int i = 0; i < N; i+=2) {
a[i] = 2*b[i];
a[i+1] = 2*b[i+1];
c[i] = 2*d[i];
c[i+1] = 2*d[i+1];
}
It seems like GHC ought to similarly be able to turn some foo :: [Int] -> [Int]
into foo :: [(Int, Int)] -> [(Int, Int)]
under the covers for a similar speedup as long as it can, as with the C compiler, handle the case of an odd length with a bit of extra code.There are limits to how much you can restructure a list that's exported outside the compilation unit (my Haskell knowledge is fuzzy here so that's probably not the right terminology). And if the list is being re-stitched in odd ways it might be a bad idea. But as far as I can tell it ought to be doable and useful in most common cases. Of course maybe it's already doing this in those cases where it can prove that it works and that's why Haskell performance generally is good but fragile.
for (int i = 0; i < N; i++)
a[i] = 2 * b[i];
for (int i = 0; i < N; i++)
c[i] = 2 * a[i] + b[i];
t = 0;
for (int i = 0; i < N; i++)
if (b[i] % 2 == 0) t += c[i];
Would be rewritten to the equivalent of: t = 0;
for (int i = 0; i < N; i++)
if (b[i] % 2 == 0) t += 5 * b[i];
Lots more info on the GHC optimizations page: https://wiki.haskell.org/GHC_optimisations#FusionHaskell also has inline-C FFI support for "type safe" performance escape hatches (in the sense that you can manually bring C constructs into Haskell's type system): https://github.com/fpco/inline-c
The only way that Haskell inescapably suffers from performance hits (that I'm aware of) is not in its laziness or lack of imperative programming support, but in its periodic GC pauses. In such cases where GC pauses are an issue, I still think you can -- in principle -- write more and more performance critical pieces of your application in a non-GC language (in fact, you could do this in Rust just as well as C/C++). You can also manually trigger a GC pass, although you cannot -- to my knowledge -- manually stop and start GC passes in your code.
This is the approach I'm currently taking in a performance critical VR application where GC pauses could absolutely be an issue (using as much Haskell as possible, with C and GC triggers as an escape hatch). And if someone could point out a flaw in my reasoning (in particular, how GC pauses might be inevitably avoided even with C FFI), I would gladly pay them money, because it's so important I not get this one wrong :).
Read about that technique from Simon Marlow of Facebook's Haskell team. Of course it would be awesome to not have to worry about that.
Strictness annotations (and associated pragmas) only change the strictness of constructors and functions defined in my modules. I still have to reason about laziness as I use almost anything from the Haskell ecosystem.
Not saying these are insurmountable, unforgivable problems, just really annoying.
Ran across Option in it the other day, though it's not used heavily. I really wish there was something like Haskell but with a runtime like Nim or Go. Perhaps that is OCaml?
I wish I could invest some time in working with Nim. It doesn't get as much attention as it deserves in my opinion, and it would really benefit from growing the community a bit.
"It only does what is needed!"
I didn't use Haskell but Nix and at least there it seemed reasonable to "not do" everything.
I enjoy writing Haskell for small hobby projects, but I doubt I would choose it for real work now that F# and Rust exist.
In Haskell when the compiler misses an optimization the performance hit is potentially unbounded, as it could think anything is a dependency. (You want the first N digits of pi? Just wait while I calculate all of them for you...)
I don't think that example cold actually happen, or at least I can't see how it would happen in Haskell.
* The ability to define control flow (structures) as abstractions instead of primitives.
* The ability to define potentially infinite data structures. This allows for more straightforward implementation of some algorithms.
* Performance increases by avoiding needless calculations, and error conditions in evaluating compound expressions."
In my several-year experience as a professional Haskell developer the first and second points are at least an order of magnitude more important than the third.
No offense, but 'performance is not as important as...' is what basically all pro-FP devs say for years, still it seems that the rest of the world thinks exactly the opposite.
Conversely, I find it hard to achieve the same performance with strict code. I think it's likely a matter of familiarity.
>Haskell is notorious in my mind for being quite easy to write obscenely slow code in.
The standard prelude is flawed in many ways. Haskell 2020 will hopefully fix this. In the meantime: the recursion-schemes library might be of great use.
If you do not need to write notoriously slow code in Haskell, just don't do it. Use libraries (containers and mtl especially great), keep state strict (a handful of bang patterns).
I use Haskell's laziness with great success (look for paper "generating power of lazy semantics" it's fascinating; look "the essence of functional programming" for even more fascination). I use Haskell's flexibility with great success (how about beating C speed ten times? how about parallelization to all cores with couple lines of code?). It is really great language.
BTW, Haskell's RTS reuse chunk type field which is needed for implementation of laziness for synchronization and it is great! This means that it can provide everything that Java and/or .Net provides and get away with twice as less overhead for it.
It's a common concern but it's a terrible critique. Laziness has many subtle benefits, but everyone whines about it because its pitfalls are decidedly not subtle.
The benefits of laziness is difficult to appreciate if you are not used to it. For a great example of the benefits it brings, please read this:
http://augustss.blogspot.co.uk/2011/05/more-points-for-lazy-...
A Haskell port of a logging library I'd originally written in Python ended up being almost 2 orders of magnitude slower than CPython 3, and almost 3 orders of magnitude slower than PyPy3.
PyPy3 resulted in performance similar to a barely-optimized C port.
https://codereview.stackexchange.com/questions/157118/a-port...
However we live in the real world and in the real world you cannot eliminate the concept of time, even in an abstraction such as functional programming. Therefore Functional programming is an utter lie.
Reasoning about the performance of a functional program is to peer through the lie and "reintroduce" time into this abstraction. This is why it it notoriously hard for functional programs to be reasoned about. Procedural programs are much more better for this in that regard.
Everything you wrote is somewhere between 90° and 180° wrong.
I've heard this a lot but still can't find a good code example to illustrate this. Any help?
This is because, believe it or not, Haskell is actually used in the real world and people care about their code not becoming broken.
Pre 1.0: every day
Post 1.0: not really, though I guess it depends on your definition of "large scale"; we've made some soundness fixes, but made sure that they were warnings for a long time first, so most people experienced no breakage.
Case in point, TypeScript and mypy. Both are adding more abstractions, more powerful types, more aspects, because people find/have fitting use cases for those features.
That doesn't mean let blah = document.getElementById("blah") ; blah.innerHTML = "..." or import requests ; requests.post(...) will become deprecated, but it means it'll be easier to express more things (like conditions/assumptions on shape or state of data, control flow, component dependencies) without boilerplate (and copy-paste), and maybe helping other developers make sure they cross all the t-s and dot all the i-s.
Does this have a cognitive cost? Yes, especially in Rust/Haskell.
Are there escape hatches? Yes, of course, like unsafe and whatever Haskell has.
Should a developer who isn't familiar with those assumptions/conditions work on the code base anyway? No, not really.
(Is Haskell ugly? Yes. :( )
https://www.rust-lang.org/en-US/friends.html has been growing at a pretty hefty pace lately!
Am upvote hoping you don't get buried.
It may get some of the facts right, but the tone is completely wrong. Cynicism is just a step or two away from nihilism. It's far, far easier to destroy than it is to create. The world needs more creators, not destroyers.
Totally off topic:
Such a simple thing to say, but I thank you for it. I often want to do good, and spent time thinking about the problems in the world and how my path might help them, but I know that I am a massive cynic in many areas. Politics being a big one.
I have always agreed with your statement about creators vs destroyers, but nevertheless I've been a loud cynic. I need to reign that in. Thank you.
Cynicism is a self-defense mechanism.
I think it's more likely that, if dependent types prove really useful, Haskell will adopt these, and people will adapt their code, rather than port everything to a new language.
As far as I can see, Idris is too much like Haskell to take its place. Porting thousands of libraries to a new language is a huge effort, so a huge advantage is required, which I don't see Idris offering.
What would we exactly lose?
>As far as I can see, Idris is too much like Haskell to take its place. Porting thousands of libraries to a new language is a huge effort, so a huge advantage is required, which I don't see Idris offering.
That is true, though. Perhaps Rust is the safer bet, even if it lacks many nice things. The sum is probably quite a lot better still.
We'd lose composability and clearer code. This[1] section of the Haskell Wiki contains a good example.
In short, with something like this:
any :: (a -> Bool) -> [a] -> Bool
any f lst = or boolLst
where boolLst = map f lst
the compiler can produce reasonably optimal code, because it doesn't have to convert the entire [a] to a [Bool], because of lazy evaluation -- when or encounters the first True, the map f lst expression stops being evaluated because of lazy evaluation.Indeed. Some people actually use Haskell, though. They even claim it's fun and productive, but having done so myself, I'm forced to be undecided on whether they're just suffering from Stockholm Syndrome.
I was somewhat disappointed not to have a followup to what work-related reasons there might be. Note also that the About page says "work at Facebook".
The inverse was not quite as true. But I still love Rust. Any time I need something performant, or I just want to play around, it's my first choice.
Instead of returning self, you could just pass a reference - you need to mutate self then just pass a mutable reference. Did I miss something here?
Returning a trait object instead of plain Self would work though.
Well, Java allows it, even if it looks a bit unglier than the Rust example.
<T extends Comparable<T>> T min (T a, T b) {
if (a.compareTo(b) > 0) { return b; } else { return a; }
}
And even without general availability of concepts (already in gcc 6.x), one can achieve it in C++ via if constrexpr. public interface Eq<A>
{
bool Equals(A x, A y);
}
public interface Ord<A> : Eq<A>
{
bool GreaterThan(A x, A y);
bool GreaterThanOrEq(A x, A y);
bool LessThan(A x, A y);
bool LessThanOrEq(A x, A y);
}
public struct OrdInt : Ord<int>
{
public bool Equals(int x, int y) => x == y;
public bool GreaterThan(int x, int y) => x > y;
public bool GreaterThanOrEq(int x, int y) => x >= y;
public bool LessThan(int x, int y) => x < y;
public bool LessThanOrEq(int x, int y) => x <= y;
}
public struct OrdString : Ord<string>
{
public bool Equals(string x, string y) => x == y;
public bool GreaterThan(string x, string y) => x.CompareTo(y) > 0;
public bool GreaterThanOrEq(string x, string y) => x.CompareTo(y) >= 0;
public bool LessThan(string x, string y) => x.CompareTo(y) < 0;
public bool LessThanOrEq(string x, string y) => x.CompareTo(y) <= 0;
}
public static class Testing
{
public static void Test()
{
var x = new[] { 3, 8, 1, 2, 10 };
var y = new[] { "mary", "had", "a", "little", "lamb" };
BubbleSort<OrdInt, int>(x);
BubbleSort<OrdString, string>(y);
}
public static void BubbleSort<OrdA, A>(A[] values) where OrdA : struct, Ord<A>
{
bool swap;
do
{
swap = false;
for (var i = 0; i < values.Length - 1; i++)
{
var x = values[i];
var y = values[i + 1];
if (default(OrdA).GreaterThan(x, y)) // Ad-hoc polymorphic call to GreaterThan
{
swap = true;
values[i] = y;
values[i + 1] = x;
}
}
}
while (swap);
}
}In any case, regardless of the fine grain details, all of them allow for to "specify the generic constraints explicitly.".
Rust is closer to Alan Turing than it is to Alonzo Church.
The code in this other post about implementing string distance metrics is also quite imperative: https://markkarpov.com/post/migrating-text-metrics.html