Hot answers tagged

46

You are comparing variable declarations to #defines, which is incorrect. With a #define, you create a mapping between an identifier and a snippet of source code. The C preprocessor will then literally substitute any occurrences of that identifier with the provided snippet. Writing #define FOO 40 + 2 int foos = FOO + FOO * FOO; ends up being the same thing ...


37

The open() function in the Python 3 library has a newline argument. Setting it to None enables universal newlines. This is the accepted way to do it, rendering the mode='U' argument redundant. Use newline=None to enable universal newlines mode (this is the default).


33

The problem with IO a = worldState -> (a, worldState) is that if this were true then we could prove that forever (putStrLn "Hello") :: IO a and undefined :: IO a are equal. Here is the proof courtesy of dolio (2010, irc): forever m = m >> forever m = fix (\r -> m >> r) = {definition of >> for worldState -> (a, worldState)} fix ...


29

There are two 'forces' here, in tension: Performance vs. Readability. Let's tackle the third problem first though, long lines: System.out.println("Good morning everyone. I am here today to present you with a very, very lengthy sentence in order to prove a point about how it looks strange amongst other code."); The best way to implement this and keep ...


24

It's possible to write asynchronous IO where you tell the OS to dispatch a disk read/write and then go do something else and then later check if it's done. It's far from new. An older method is using another thread for the IO. However that requires that you have something to do while that read is being executed and you will not be allowed to touch the ...


19

The I/O schemes you are describing are in current use in computers. why the CPU actually has to stay there, practically not doing anything else than just waiting for IO? This is the simplest possible I/O method: programmed I/O. Many embedded systems and low/end microprocessors have only a single input instruction and a single output instruction. The ...


18

java.io uses Streams while java.nio use Channels and buffer, The most important distinction between java.io way and java.nio way is, how data is packaged and transmitted.java.io deals with data in streams (one byte at a time), whereas java.nio deals with data in blocks. Processing data by the block can be much faster than processing it by the (streamed) byte ...


18

There are two issues at play here: Issue #1: C is a statically typed language; all type information is determined at compile time. No type information is stored with any object in memory such that its type and size can be determined at run time1. If you examine the memory at any particular address while the program is running, all you'll see is a sludge ...


18

Because input and output are unreliable. Exceptions are, in part, an acknowledgement that there are going to be conditions which the software cannot reasonably recover from. Premature end-of-line termination, syntax error or any number of validation error conditions, Inputs are too long or large to reasonably accomodate, Keyboard gets unplugged, Hard ...


15

The performance overhead of writing lots of data to disk isn't the execution speed of your code, but rather the physical limitations of the actual hard drive. Doing it assembly won't give you a noticeable performance increase. Your best bet is to either log less data (recommended, if you're logging that much stuff how useful can it be) or change the drives ...


15

The Haskell optimizer is allowed to freely manipulate calls to pure functions as long as the result remains the same. For example, if it can see that you are calling sqrt on the same number 100 times, it can cache the returned value and only call it once. If it can see that you never actually use the result of that function, it can choose to not call it at ...


15

I would write the if-statement slightly different, so it is taken when the input is successful. for (;;) { cout << ": "; if (cin >> input) break; cin.clear(); cin.ignore(512, '\n'); } It's shorter as well. Which suggests a shorter way that might be liked by your teacher: cout << ": "; while (!(cin >> input))...


15

What you have to strive for is avoiding raw loops. Move the complex logic into a helper function and suddenly things are a lot clearer: bool getValidUserInput(string & input) { cout << ": "; cin >> input; if (cin.fail()) { cin.clear(); cin.ignore(512, '\n'); return false; } return true; } int ...


14

Unfortunately, the answer is, "it depends." It would be easy for you to write a small program to empirically determine the times of both async and sync reads. It will depend on lots of factors. Are they stored on spinning disks, SSD, or a network drive? What kind of CPU are you using? How many sockets/cores? Are you running in an VM or bare metal? Are ...


14

Simplest possible example: printing "Hello, world!" changes the state of the system, because the console now displays "Hello, world!", and earlier it didn't. Not only have you changed the state, it's actually impossible to change it back, since you can't un-get characters from a terminal! That's about the most serious side effect possible.


13

Your understanding is wrong. Several Linux processes can write to the same file at once (and what happens then might be unspecified, except when the processes overwrite different segments of that file). And some other Linux process (e.g. your browser) can read a file which is written to. You could adopt a convention to avoid that. For example, you could use ...


12

I wrote a blog post on the topic of how to model IO as a form of asymmetric coroutine communicating with the runtime system for your language. (It is admittedly the third part of a series) http://comonad.com/reader/2011/free-monads-for-less-3/ That post covers a bit of why it is awkward to reason about the semantics of 'world-passing'.


12

Here's a trivial answer: any change to the state monad's state is due to any actions ran in the monad. If indeed the “WorldState -> (a, WorldState)” explanation claims the same property, with WorldState being a pure value that only the IO monad changes, it's wrong. Time changes, the content of files, the state of handles, etc. can change independently of ...


11

The Model is generally responisble to reading from/writing to the file system or database.


10

Because exceptions (as opposed to error code return values) cannot be ignored. The typical code for i/o calls before exceptions, was usually written in terms of printf/scanf/gets/puts. These functions return values that allow the developer to check for errors, but that is not trivial. Most developers, knowing the error handling is not trivial, simply ...


10

I want to write tests for it. What you are intending to test? I want to use TDD. I'm refactoring a parser and want to test the 'parse()' method. So the aim is to clean things up. I would argue that refactoring legacy code isn't 100% compliant w/ TDD. Bad code restricts testing. More importantly - intention to clean it up (the drive - reason for ...


9

Async has 3 main advantages: It lowers CPU utilization. This could be useful if you are also doing CPU-heavy operations with data you just read. Using some kind of async infrastructure makes the code easy to paralelise. Especially if you are reading lots of files. By sending multiple read-write requests to OS, OS and HW can re-order those operations to be ...


9

It's not so much that for(;;) is bad. It's just not as clear as patterns like: while (cin.fail()) { ... } Or as Sjoerd put it: while (!(cin >> input)) { ... } Let's consider the primary audience for this stuff as being your fellow programmers, including the future version of yourself who no longer remembers why you stuck the break at the ...


9

At the lowest possible level from a user program running in some operating system, the libc is making system calls (or syscalls). These are often a single machine instruction (often SYSCALL or SYSENTER) which is given some parameters and which switches the microprocessor to supervisor mode in a controlled way. Then the kernel is processing the parameters and ...


9

Have faith that the processing of other stuff while waiting for I/O is quite streamlined, close to as streamlined as possible. When you see that your computer is waiting for I/O only 12.1% of the time, it means that it is in fact doing a lot of other things in parallel. If it really had to wait for I/O without doing anything else, it would be waiting for ...


8

See Tackling the Awkward Squad. The big reason is RealWorld state models of the IO monad don't work well with concurrency. SPJ in this readable classic favors using an operational semantics to understand it.


8

Because at the moment when printf is called and does its job, the compiler is no longer there to tell it what to do. The function doesn't get any information except what's in its parameters, and the vararg parameters don't have any type, so printf would have no clue how to print any if them if it didn't get explicit instructions via the format string. The ...


8

To improve efficiency, I wanted to have one thread pool perform the I/O section and have it pass tasks to another thread pool that performs the CPU section. That way, it's unlikely that all threads will be stuck either hogging the I/O or hogging the CPU. You don't actually need two thread pools to pull this off, and doing it that way can be ...


8

Yes. The DMA controller takes ownership of the bus for the duration of the transfer. That said, I feel obliged to point out that at least on PC-based machines, DMA controllers have been almost entirely obsolete for quite a while now. On a reasonably modern machine, the DMA controller is used only for I/O to/from floppy disks (and only "directly" connected ...


7

It depends on how big your lines are. By default, BufferedReader uses an 8k buffer (see source). This means that it will attempt to read 8K at a time from the Readerthat it was constructed around. You can read as many lines as will fit into that 8K buffer, without going back to the underlying Reader. Edit: As a general comment, do not use FileReader. ...


Only top voted, non community-wiki answers of a minimum length are eligible