172 points · by ryannielsen · 15y ago · 43 comments
In Haskell:
zip :: [a] -> [b] -> [(a, b)]
zip [] _ = []
zip _ [] = []
zip (x:xs) (y:ys) = (x,y) : zip xs ys
Note how each iteration needs to check both lists for emptiness.In a more advanced type system (or using more advanced type hackery in Haskell) you can have length-indexed lists. That is: lists that have 2 type parameters or "indexes" instead of 1. The 1 is usually the type of element inside the list, the extra 1 is a natural number indicating the length of the list.
So the function zip becomes something like:
zip :: List N a -> List N b -> List N (a, b)
zip [] [] = []
zip (x:xs) (y:ys) = (x,y) : zip xs ys
The compiler checks the code and verifies, at compile-time, that both the input lists and the resulting list are all of the same length. This also means that you only need one runtime emptiness check instead of 2. If the N is concretely known at compile-time, you may need 0 (though that case might be caught by inlining/loop unrolling optimizations anyway).Also, in this example you're using a singly linked list, which is usually a performance loss compared to a more appropriate data structure. CPUs are designed to favor contiguous arrays.
Well, you can choose any two of: 1. Fast (less run-time), 2. Safe (cannot crash), 3. Simple types (None of the advanced type hackery). Many choose 1+3 or 2+3, but advanced types let you choose 1+2 which in many cases is remarkable and somewhat surprising that it is even possible.
Also note that runtime checks, in many cases, do not give you safety. For example, normally, you have an array indexing operation like:
readArray :: Array a -> Int -> IO a
Ignore the "IO" if you are unfamiliar with Haskell's IO type. This is unsafe whether or not you have index bounds checking. A runtime check will only convert one kind of error (corruption/segfault) to another (runtime exception).In these (common cases), your only option of getting safety is advanced type hackery. Something like:
index :: (size:N) -> Array size a -> Fin size -> a
where Fin N is the type of integer ranged between 0 and (N-1).> Also, in this example you're using a singly linked list, which is usually a performance loss compared to a more appropriate data structure. CPUs are designed to favor contiguous arrays
Nothing about this type hackery is specific to singly linked lists, and advanced type hackary is applicable for pretty much any data structure. Also note that the singly linked lists used in zip may not actually be represented by pointer-chasing singly-linked lists. They may be "fused" together into efficient loops that process the input directly.
If you wanted truncation and had no type-level knowledge about a relationship between the list lengths, you would explicitly compose list truncation of the longer list with the zipping.
But if you have some sort of known relationship between the lengths of the lists, not just equality of the lengths (as specified above), you can avoid the check.
For example:
zipTruncate :: List (1+ N) a -> List N b -> List N (a, b)
zipTruncate _ [] = []
zipTruncate (x:xs) (y:ys) = (x, y) : zipTruncate xs ys
This also has just one check, and is verified safe by the compiler, and truncates the single extra element from the first given list.With dependent types, you can even say something like:
zipTruncate :: List (someFunc N) a -> List N -> List N (a, b)
But I am no expert on dependent types, and do not know what can/cannot be done with application of functions at the type-level.It is only leaky if you are exposed to the statefulness of the underlying machine.
Haskell's pure code does enjoy the abstraction of purity without exposing the non-pure primitives from which it is exposed. Haskell's non-pure code is marked as such, and not supposed to be abstracted away from the nature of the underlying machine. I'm not sure what abstraction leak you're referring to. Can you give an example?
More generally, the fact that execution time and memory usage (tail recursion!) sometimes depend on how well the compiler can turn your stateless algorithm into a stateful one, in ways that don't make sense from the perspective of the abstract machine.
In the end, it's all a few billion transistors that need to be switched on and off at just the right time. C is as far away from that as Haskell is.
I don't think what you're saying is intrinsic to FP. There are static analysis tools for non-functional languages. At the end of the day, everything is getting turned into an abstract syntax tree, so style should be irrelevant.
Do you mean pure (side-effect free) functional languages?
In Haskell you happen to know about statelessness from the types, which is an additional bonus. But other statically type languages like Eiffel are also pretty well optimizable.
Apologies for the confrontational tone, but someone making that kind of mistake out of ignorance is understandable. Insisting on wrong thinking after having it explained in detail why it's wrong, isn't.
If you can't live with the fundamental design principles behind C/C++ then the correct approach is to not use them. Don't ask the compiler writers to go against those principles.
"We all know that in practice" type assumptions are exactly what make code difficult to port and/or maintain and developers should really stay away from them. Or at least, if you really want to make such assumptions (for example, for performance reasons), make sure that that (1) you know exactly what you're doing and (b) test for their validity at compile time or runtime and provide fallback code that always does the "right" thing.
So the existence of that tool doesn't contradict the statement of the article.
gcc still gets the pointer dereference and assignment to what a pointer points to, due to deferring assignments. these edges, idioms of any lang needs to be looked at with academic eyes. :-)
llvm is an excellent tool, hats off, and thanks.
if (i < 0 || buffer+i-128 >= buffer)
... instead of if ((i < 0) || (i >= sizeof(buffer))
?Instead, consider it from the point of view of probability.
Even if probability of any single programmer writing an exceedingly stupid piece of code is vanishingly small, the number of programmers writing new code daily is so big, that mistakes of vanishingly small probability end up being quite common indeed.
To given a real example: consider that Apple undoubtably employs only the finest programmers for their OS group and yet every iOS release is jailbroken quite quickly due to a piece of code which had a security bug.
Even within a much smaller scope of a single application, all web browser from Microsoft, Apple, Mozilla (and sometimes Google) are regularly compromised via security bugs despite huge investments from all those companies into security.
Toss in the fact that many programmers actually like doing things in unnecessarily clever or novel ways and inevitably the clever code is more likely to be buggy than boring code.
Bugs and crappy code is a statistical certainty, especially in languages like C and C++ that give you so many ways to shoot yourself in the foot.
Unrelated to the issue, but the superfluous parenthesis added in the second example are interesting. I think every C coder has a level of comfort with the 15 sets in the operator precedence rules, and beyond that they throw parenthesis at it. I'm fine with the rules until I use a <<, >>, &, ^, or |[1]. Then I drag out the parenthesis.
[1] I swear the positions of the ones I named are placed alphabetically rather than in relation to their mathematical function.
:(
Therefore, buffer through buffer+1 would be valid pointers, but unless they can prove that i-128 is <=1 they can safely assume that the final pointer can be more than 1 past the buffer.
If it was just a pointer (not an array) they could do the same analysis if the pointer was mallocced right then in the same function with a constant size. More likely though, the pointer would be a function argument and then they would not know where the object boundaries were without doing interprocedural analysis (which I assume is outside of the scope of this post) and some other additional propagation (so technically within the C99 spec, but I doubt you would see an optimization that actually would do that).
- macro expansions
- the author took an example from a larger function and simplified it into a minimal test case. For example, there might be a
#define BUFSIZE 128;
...
j = buffer+i;
...
if( (i < 0) || (i-BUFSIZE >= buffer))
Still weird (i - BUFSIZE could underflow), but more believable.