for (auto item : {})
and then filled in the first sequence of numbers that popped into his head.390 karma · joined April 17, 2014
for (auto item : {})
and then filled in the first sequence of numbers that popped into his head.>What frustrates me is to see the rigidity with which it is followed, and the failure to understand the world in a different way. There is a different world out there that doesn't mind an implicit conversion from void pointers, and they're not "wrong".
I have seen and lived in the world where casts from void* are common, and where making those casts implicit is a convenience (and that world is not the world of C++). I understand that world. I understand that viewpoint. I just strongly disagree with it.
You could use the exact same argument against any type-safety feature: inserting "pointless" forward declarations, inserting "pointless" const qualifiers, etc., to "satisfy a whiney compiler."
The thing is, implicit conversion from void* is plainly unsound, type theoretically speaking. It has certain advantages, but is not necessary in order to have those advantages. For example, it makes use of malloc easier, but one could also make the vast majority of uses of malloc easier with something like
#define ALLOC(TYPE,N) ((TYPE*)malloc(N*sizeof(TYPE)))
Or at least, one could if C had a remotely regular type syntax and/or actual type genericity. In contrast, you actually can write template <typename T>
T* alloc(std::size_t n) {
return static_cast <T*> (malloc (n * sizeof (T)));
}
in C++, and it's even straightforward to add additional logic like overflow detection. Mark it inline and stick it in a header, and it's effectively the same as the above ALLOC macro, except that it actually works. Now, contrast int* array = malloc(256*sizeof(int));
with int* array = alloc<int> (256);
The C++ expression is simpler. Now, if you change the type of the array, but forget to change the allocation expression (for whatever reason; maybe you're using the absurd convention of declaring all your variables before you start initializing and using them): char* array = malloc(256*sizeof(int));
// vs
char* array = alloc<int> (256);
You get a type error with the C++ version, and the C version silently compiles. Not too much of an issue in this case -- you'll just waste a bunch of memory -- but go from char to int instead of int to char, and now you've got buffer overflows.As for the argument made elsewhere in this thread that explicitly casting the result of malloc in C can mask the fact that malloc has been implicitly delcared, that's a language bug -- one that was fixed more than fifteen years ago.
When C is the right tool, assuming that it ever truly is, C++ is a vastly better substitute than Java or C#. C++ uses the same machine model as C; Java and C# do not.
Than what? Than a freshly designed C-like language? Yes. But ISO C wasn't an effort to invent a new language. It was an effort to standardize existing practice, and provide a platform for improving C. One of the core goals of ISO C is to maintain every last bit of backward compatibility possible, which is why integer widths are not precisely specified: had they been, multiple vendors' implementations and the code that was written for them would have broken.
But to your main point, I agree: explicitly sized integer types are almost always what you should use. For example, don't store a pointer in an unsigned long (and certainly not a signed long); store it in a uintptr_t, or hell, just store it as a pointer. In fact, the fundamental types like int, long, etc. are effectively just shorthand for int_fast16_t, int_fast32_t, etc., but without the mnemonic value.
#if (ULONG_MAX < UINTPTR_MAX) && !defined (SUPPRESS_TRUNCATION_ERROR)
#error Truncating pointers to long is a bad idea here
#endif
in some source file or another, just so you have some indication whether or not things are going to break when you change the build environment.It's silly for Windows to do something a certain way just because that's not how Unix does it?
What's silly is assuming that long and unsigned long are more than 32 bits wide, since neither C nor C++ has ever guaranteed anything more.
The issue isn't with the example you gave, but with the idea in general that being able to produce a term of a given type in Haskell means that that type is necessarily inhabited.
>This is true, in a sense, but also a little bit misleading I think, since technically every type in Haskell is the set of terminating value with that type plus _|_
Well, ⊥ is empty, so naturally every type is itself plus ⊥. In fact, that leads to an important observation, which is that any computation in Haskell could potentially be non-terminating, not just those with type Void—and so it's really not the inclusion of the bottom type that causes things to break down, but the ability to produce non-terminating computations (more specifically, non-coterminating, i.e. non-productive "lazy" computations).
Unfortunately, the alternative—making it impossible to produce non-terminating computations—is more than anything a matter of rejecting everything the compiler can't prove terminates, which is kind of limiting, termination being undecidable in the general case. On the other hand, the sorts of computations humans design are generally much more well-structured than an arbitrary Turing machine, and so probably much easier to prove (co)termination for.
inhabitantOfZero :: Void
inhabitantOfZero = fix id
(Side note: the empty type can also be interpreted as the type of non-terminating computations, and in fact typing 'fix id' into ghci will cause it to hang)It turns out that 𝟎⁰ = 𝟏 is true, though, and if I'm not mistaken, this is true of semirings in general (where the exponent has a natural interpretation; of course you can define exponentiation this way for any semiring you like). This sole inhabitant is the empty function, which is easiest to explain in set-theoretic terms: if you define a function from A to B to be a subset of A × B such that each a ∈ A appears exactly once (for example, the negation function on Bool would be the set {(true, false), (false, true)}), it's clear that there's exactly one function from the empty set to the empty set, because there is only one subset of ∅ × ∅ (i.e., ∅) and for this set the above property is vacuously true.
For completeness, here's what the empty function looks like in Agda, which treats types much more carefully than Haskell (to understand why, look up intuitionistic logic/type theory and the Curry-Howard isomorphism):
module EmptyFunction where
data ⊥ : Set where
-- No constructors, since ⊥ is empty
inhabitant-of-𝟎⁰ : ⊥ → ⊥
inhabitant-of-𝟎⁰ ()This depends on what equivalence you're using, and the only one in which it's true (definitional equality) isn't very interesting. Extensionally, the functions are identical.
I just used the expansion given in the parent. It also makes it apparent that List is the closure.
And they're not limited to regular languages; with the right computational tricks (lazy evaluation, coinduction, whatever you want to call it), it can be used with context-free languages in general: http://matt.might.net/papers/might2011derivatives.pdf
In a sense, yes. "×" denotes the product of two types— i.e., the type of pairs of one value of the first type, and one of the second. "+" denotes the disjoint union of two types, the type of values which are taken from the first type or the second type. Importantly, when you have "a + a," taking a value from the left "a" is distinct from taking a value from the right "a."
>So then why is the Bool type 1 + 1 == 2? Shouldn't it be 1 + 0 == 1 if you want to map the possible states?
"0," "1," and "2" here do not denote states; rather, they denote types. In particular, "0" is the type with zero values, "1" is the type with one value, "2" is the type with two values, etc.
The reason that "1 + 1 = 2" is true is that there are two ways to form a value of type "1 + 1:" take the one possible value from the left "1," or take the one possible value from the right "1." The Bool type, by definition, has two values, so it needs to be given by the type "2," or equivalently, "1 + 1."
>Same question for "maybe" that seems to work like in Rust or Swift - shouldn't it be a + 0? If not, what does "a or unit" mean?
"a + 0" is, as the algebra suggest, just "a." This is because the only way to form a value of type "a + 0" is to use a value from "a;" there are no values in "0" to choose from. The Maybe type is effectively the identity type plus a single "None" value. Thus, we call it "a + 1;" there is a "Some" for each value in "a," and a None for each (i.e., the only) value in "1."
L a = 𝟏 + a × (L a)
= 𝟏 + a + a² + a³ + ⋯
and substitute 𝟏 for a: L 𝟏 = 𝟏 + 𝟏 + 𝟏² + 𝟏³ + ⋯
= 𝟏 + 𝟏 + 𝟏 + 𝟏 + ⋯
= 𝟏 + (L 𝟏)
you get ℕ: ℕ = 𝟏 + ℕ
The zero-power rule (x⁰ = 1) from classic algebra also holds; there is exactly one function from 𝟎 to any type (or in set-theoretic terms, from the empty set to any set).There was an interesting paper on "closed semirings"[0] posted here a few days ago. Clearly, the product and coproduct on types form a semiring, and interestingly, List is the closure!
>In semirings where summing an infinite series makes sense, we can define a* as: 1 + a + a^2 + a^3 + ...
>In other semirings where subtraction and reciprocals make sense we can define a* as (1 - a)^-1
Suddenly the "generating functions" from my combinatorics course make so much more sense. It was never about functions at all! It was about reusing our knowledge of algebra on the real field and power series to manipulate a closed semiring of combinations.
In retrospect, I think it would have been less confusing to use the abstract algebra from the outset.
Why in the world should this be true? I'd much sooner try to weaken this requirement than the additivity requirement or the axiom of choice. For example, I imagine restricting measures to (unions of countably many disjoint) (path-)connected subspaces of the ambient topology would solve the problem just as handily, without making any compromises on how well the math models our intuitive notion of measure. On that note, I suspect that to really have a meaningful notion of measure, one really needs to have at least a topology, if not an outright metric space.
Can anyone more versed in this area comment on this?
I haven't run the math, but I don't believe introsort fixes this. It's a constant-factor optimization.
status_t foo (result_t (*result))
{
status_t status = good;
resource1_t r1;
if (failed (status = get_r1 (&r1)))
goto end;
resource2_t r2;
if (failed (status = get_r2 (&r2)))
goto cleanup_r1;
resource3_t r3;
if (failed (status = get_r3 (&r3)))
goto cleanup_r2;
status = get_result (result, r1, r2, r3);
cleanup_r3:
release_r3 (r3);
cleanup_r2:
release_r2 (r2);
cleanup_r1:
release_r1 (r1);
end:
return status;
}
Personally, though, I prefer using C++ and destructors (and, where appropriate, exceptions): result_t foo ()
{
// Allow exceptions to propagate
auto r1 = get_r1 ();
auto r2 = get_r2 ();
auto r3 = get_r3 ();
return get_result (r1, r2, r3);
}
Exceptions aren't always appropriate, but the C++ still usually ends up a little cleaner. I would love to see something like Haskell's Maybe monad that lets you write code like the above, but returning status information instead of throwing exceptions. void foo (char bar [42]) {
// ...
}
then within the scope of foo, bar will be a pointer to char, not an array of char. You can, on the other hand, write void foo (char (*bar) [42]) {
// ...
}
in which case bar will be a pointer to array of 42 char (and notably, not a pointer to a pointer to char!).C does some very strange things. There usually is (or at least was) a good reason for it to do so, but especially if you're a beginner, you need to be on your toes if you really want to use it well.
Many powerful systems are unfamiliar and difficult to use— but a system that is unfamiliar and difficult to use is by no means necessarily powerful.
At any rate, the issue isn't that Unix is difficult to use, because it isn't. What's difficult is using it well. What's difficult is learning all the idiosyncrasies, all the details you have to get right to write good software in the Unix ecosystem. What's difficult is learning when and why
rm *
does not do what you expect, recognizing the flaw in code like mv "$PROJECT_ROOT"/* .
that can nuke your entire machine because the default semantics of the Unix shell are... well, questionable.The thing is, using Unix well isn't difficult because the individual things you have to learn are difficult; the problems with the above commands are very simple and easy to address. Using Unix well is difficult because these problems arise goddamn everywhere.
>Inconsistent command names shouldn't be a difficulty - shell commands are like any other language, whose vocabulary is quickly learned with repeated use.
>I'd consider it generous to see a mention of shell redirection in cat's manual, since that's done before it ever gets executed; in general, interactions between commands can't be exhaustively documented because they are numerous, and Unix assumes you can put two and two together.
Excuses. Inconsistent anything is a difficulty. The user of a system should not have to compensate in any capacity for the failure on the part of the system's designers to ensure consistency— of names of all things. That interactions between parts of the same system are so complex that it would be an act of generosity to document them is not the mark of a powerful system; it is the mark of a poorly designed one.
And that's the thing: Unix is poorly designed. Maybe it was revolutionary nearly a half-century ago, but if someone unveiled an operating system, today, built on passing around and interpreting ASCII-encoded strings, with the occasional undecorated integer thrown in for kicks, they'd be laughed out of the room.
>Thanks to this "lowest-common-denominator" type of interface design, ease-of-use seems to have massively replaced learning, dissuading and distancing users from having control of their machines at a time when such control is becoming increasingly important.
This is happening, to a degree. However, there is a very important distinction to be made between the sort of "ease of use" that comes from reducing a system to a minimal high-level mode of interaction, and the sort of "ease of use" that comes from fixing the mistakes of previous iterations of the interaction model. Replacing the process of learning the aforementioned inconsistencies, pitfalls, and general frustrating complexities of Unix and its descendants with a system of equal or greater power that is genuinely easier to use is not a bad thing.
It's just really, really freaking difficult.
Or at least, no one seems to have done it yet.
I think it would be more appropriate to use a compiler macro here.
And? This is true of code in languages without macros, too. You have too learn all the vocabulary, all the types they use, all the functions, all the structure of the program— macros are just a tool for taking these domain-specific things and packing them into a denser syntactic abstraction. A well-written macro improves readability in both the short and long terms.
I mean, say I write a couple of macros to deal with a database and I write code like
(with-sql-connection ("localhost" ...)
(select *
from "customers"
where (= "lastname" "Smith")))
Do you really think that's less readable than the nonsense you'd have to write a typical "framework," or worse, building the command string by hand?No. How would macros break homoiconicity? They expand into atoms and lists (and other datatypes), the same stuff of which macro-free programs are made.
>And making maintenance more difficult?
No. Unless you intentionally write unmaintainable macros. It's the same as if you write unmaintainable functions, classes, etc. They're just abstracting a different thing— syntax.
>aren't you re-inventing a new language with macros?
No, you're expanding the language; you're just expanding the grammar instead of the vocabulary.
>Where does the "First rule of the macro club" coming from? When should you break it?
What is the "first rule of the macro club?"