/dpt/ - Daily Programming Thread

Old thread: What are you working on Cred Forums?

Other urls found in this thread:

youtube.com/watch?v=zBkNBP00wJE
std.dkuug.dk/JTC1/SC22/WG14/www/C99RationaleV5.10.pdf
msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline
hackage.haskell.org/package/base-4.9.0.0/docs/Foreign.html
twitter.com/SFWRedditGifs

1st for Go > *

Is this a data leak in c++?

int x;
int* y=&x;
return 0;

>Go > nothing
Agreed.

>tfw you never will understand why macros is needed in lisp
I will never have time to really learn CL to understand why macros are used except for the obvious ones

No heap allocations were made, so there is nothing that could leak.

thanks ;D

All of the declared stuff is local, therefore on the stack, therefore gets cleaned up when you leave the scope.

Still working on my metronome.
I have decided that Web Audio API is shit.

what can I do with c?

Anything your heart desires unless you're planning on averaging two (2) integers.

Write a compiler for a better language.

what can't you do with c?

Combine it with vowels and other constanants to create a "word"

C --> Python?
You mean starting with C, then going to Python?
Don't start with C. Start with C#. If you want to learn Python, Python is actually easier (in my opinion) to learn than C#.
Absolutely do not start with C, though. C and C# are entirely different monsters.

words are antiques. it's all about the dwords and qwords nowadays.

>Don't start with C. Start with C#.
That is fucking terrible advice.

m8, it's easy as shit. IIRC:
var audio = new Audio()
audio.src = 'some_url';
window.addChild(audio); // ??
audio.play();


also,

It's for when you have a function that you wish was even slightly different and you can't figure out how - or decide it's too much work - to do it the normal way.

For instance, in Racket the hash-ref procedure only returns a single value and accepts only a single key. If you wanted to grab a whole bunch of values at once, you could write a macro that would change its behavior rather nicely.

No it's not.
You aren't thinking like someone that isn't a programmer. Sure, it would be IDEAL to start at a low level and then move upwards in terms of truly understanding programming and becoming good at it, but beginners learning C first are going to try, get frustrated, and then quit. It's much better to start with an easier, higher-level language that deals with shit for you to become comfortable with programmatic thinking before moving onto lower level languages.

Macros take code as input, not the results of running code.

Couldn't you just do that with a function instead?

It really depends on the type of learner you are.

Top-down and bottom-up are both valuable, and you usually end up doing a mix of both in reality.

Yeah, I know what they do and I can see that it might be useful to influence the abstract syntax tree but I can't for the life of me see why you would do that instead of using functions (excluding the obvious ofcourse)

>beginners learning C first are going to try, get frustrated, and then quit
I started with C and thought it was great.

#include

int main()
{
int x=0;
std::cout

The funny thing about Lisp is that due to homoiconicity the line between functions and macros is very blurred. So when people say Lisp is awesome because of macros, it's really awesome because of homoiconicity. Macros just make it so you don't have to manually quote and eval.

>you should begin with C
>you should begin with python
>you should begin with C#
How about that people start with a sane language?

Yeah yeah, everything's easy if you just do exactly what and how the API wants you to. But if you want something just slightly different, or your mental model of the problem domain doesn't quite mesh with the API writers model, you find yourself wrestling with the API and you end up with a kludge.
I tend to not be comfortable on a high level.

This is why code should be pure

I'm no sepplesfag, but I'm pretty sure those 2 x++s are sequenced compared to each other, meaning that it's undefined behaviour.
>Why is c++ so shit, /dpt/?
Lots of reasons, but that isn't one of them.
From your program particularly, C++ iostreams are a fucking joke.

I don't know what language you work with, but I'm sure one could construct an example which makes it look shit too.

I started learning programming with C++, and it was the best thing.
>I learned a lot about memory, and other low level stuff
>I learned about OOP
>It wasn't frustrating at all
Now I'm a java programmer and I'm still having the "I know that from C++ so I just saved myself a lot of trouble" moments
If you find coding frustrating maybe it isn't for you? Just throwing ideas.

Then you're very lucky
I'd say that recommending high-level languages is a safer bet- If they thirst for knowing more right away, they'll jump to C++ or C or some other lower level language in a few weeks
If they don't, they'll have the chance to get acclimated to how programs work before going on to the lower-level functionality.

this desu

I started with C.

>I'm a java programmer

VirtualBox is a Virtual Bitch that doesn't like to play nicely with Visual Studio's debugger... or really, with any form of networking at all.

So yeah, I got nothing useful done today. How's everyone else doing?

Look what the big colleges start with; C, (Harvard) Python (Stanford) Jave ( UofPrajeet)

There is literally nothing wrong with Java

Ok, can someone finally explain this? I don't understand.

For starters, C++ and C are completely different languages, as your post seems to be implying that they aren't.
Secondly, teaching OOP to beginners is a terrible idea, as they will take that fundamentally flawed shit seriously.

Why doesn't lefty have a horn to suck ?

>try catch

>tfw faster than the most used image handling crate

cubic::image_0x 13,381,337 ns/iter (+/- 1,542,263)
cubic::image_2x 54,913,422 ns/iter (+/- 2,307,220)
cubic::image_4x 182,939,908 ns/iter (+/- 5,327,154)
cubic::picto_0x 5,740,871 ns/iter (+/- 502,457)
cubic::picto_2x 31,988,531 ns/iter (+/- 1,712,721)
cubic::picto_4x 106,429,946 ns/iter (+/- 4,825,844)
gaussian::image_0x 42,953,499 ns/iter (+/- 2,079,527)
gaussian::image_2x 169,449,628 ns/iter (+/- 5,002,680)
gaussian::image_4x 586,924,804 ns/iter (+/- 38,119,622)
gaussian::picto_0x 23,629,491 ns/iter (+/- 2,826,326)
gaussian::picto_2x 113,357,988 ns/iter (+/- 6,666,321)
gaussian::picto_4x 377,487,886 ns/iter (+/- 22,168,297)
lanczos3::image_0x 39,250,499 ns/iter (+/- 11,437,446)
lanczos3::image_2x 160,409,285 ns/iter (+/- 9,122,349)
lanczos3::image_4x 531,427,481 ns/iter (+/- 25,366,899)
lanczos3::picto_0x 26,490,286 ns/iter (+/- 3,656,158)
lanczos3::picto_2x 131,921,548 ns/iter (+/- 15,352,566)
lanczos3::picto_4x 421,148,075 ns/iter (+/- 10,492,415)
linear::image_0x 7,761,669 ns/iter (+/- 958,131)
linear::image_2x 30,445,293 ns/iter (+/- 1,849,317)
linear::image_4x 101,924,598 ns/iter (+/- 4,415,125)
linear::picto_0x 5,150,302 ns/iter (+/- 547,642)
linear::picto_2x 25,628,937 ns/iter (+/- 1,928,336)
linear::picto_4x 86,403,188 ns/iter (+/- 3,505,380)
nearest::image_0x 5,050,630 ns/iter (+/- 277,353)
nearest::image_2x 30,389,495 ns/iter (+/- 2,150,002)
nearest::image_4x 101,588,167 ns/iter (+/- 4,633,871)
nearest::picto_0x 439,042 ns/iter (+/- 56,110)
nearest::picto_2x 7,057,137 ns/iter (+/- 662,431)
nearest::picto_4x 29,485,564 ns/iter (+/- 1,635,690)

People shitting on C++ should watch this talk: youtube.com/watch?v=zBkNBP00wJE

I just came to the realization that it's probably too late in my career to pivot into a developer role. I'll probably just have to support my child on a SQL monkey's salary and spend the rest of my working days churning out ad-hoc Crystal Reports.

So, pretty good.

for your metronome, you only need some audio file and a way to play and pause it. I don't see how that is difficult.
I know one has problem trying to learn/create things, but this, in particular, is not difficult.

from what I've read, vbox doesn't play nice with windows, at all. anyway, I guess you could ask, I have a bit of experience messing with windbg on vbox...

There's nothing good about it either.

>got nothing useful done today
Same here. I'd like to blame it on VirtualBox or something but in reality I'm just lazy.

Why would I use C++ when I can use Rust?

> 2nd week CS
>Java as first lang
> Prof talks about classes
> whats a class ?
> you have many of them
>whats a class ?
>you have sub classes
>whats a class ?
>animal is class and dog is sub class
>this kills the student

>listen to this talk from the annual cultmeeting
How about no

>Shitty JVM
>No unsigned integers
>No pointers
>No tuples
>Half-baked streams
>UTF-16
>Checked exceptions
>No free functions
>Forces OOP
>Supports OOP
>Bloated standard library
>No outstanding features that would make you want to use it over something else

>Not linking to Based Bjarne.

>3 billion devices

C runs on more devices.

the x++ on the right is done before the x++ on the left

>Why would I use C++ when I can use this other poorly conceived mess
True, I suppose

I don't have audio files. I don't want audio files. I want the metronome to generate the sound. Like a real metronome.
I can add optional support for external sound files as a bonus feature when everything else is done.

rust has no libraries though

you obviously have no idea what you're talking about

but why?

Compatibility with existing libraries.
General maturity, and better optimizing compilers.

It gives moeneys so you can hate all you wan
>completely different things
a computer and a mug are *completely* different things
C and C++ most definitley aren't *completely* different things
They are very closely related things.
With the OOP thing I actaully might agree, only because of the way it's taugth.
I don't know why everyone everywhere in academic enviorments as well as in books or tutorials teach it the very wrong way.

Are you saying that none of those are true about Java?

But it can use any C and C++ librar on top of the Rust ones!

Check and mate.

My example wasn't particularly a good one, I admit, but the desire to change how a procedure operates is still there.

(define-syntax-rules (hash-ref* hash k0 ...)
(values (hash-ref hash k0) ...))

versus
(define (hash-ref* hash . keys)
; something like this?
(map (lambda (k) (hash-ref hash k)) keys))


I apologize if the second code block doesn't work out. I'm don't have a REPL at the moment

>Interpreted
>GC
>Arrays aren't necessarily contiguous in memory
>Inconsistencies throughout the language and standard library
At least on 6+ abstraction layers :^) (pic related)

C doesn't actually run on anything.

>java
>abstraction

I also, apparently, don't have a way to play and pause. I have a way to play and stop. Now i'm going to have to kludge together a pause functionality from that, and it's going to be ugly.

As long as you write a wrapper around it first. Making a C library compatible with C++ is so trivial that most C library authors will add the #ifdefs in by default.

>Interpreted
Java is JIT compiled, not interpreted.

3 BILLION

B
I
L
L
I
O
N

C compilers run on a lot of stuff though.

>C++ library
Using FFI with C++ is a fucking nightmare, and most of the time, people have to write a C wrapper over them.
It's not other languages fault: it's C++'s fault.

>C and C++ most definitely aren't *completely* different things
They have diverged massively at this point. It's basically the same as calling scheme and lisp the same thing.
C++ is not a superset of C, and hasn't been since the 80s. I heard that the latest C++ standard is going to be removing keywords that make this even more true, not to mention all of the C-only features that were added in C99, C11 and the upcoming C2X.
Whenever you bring up C++ in a discussion about C, it's a clear sign that you're a fucking idiot.

Name one device that can run programs, but cannot run programs written in C.

3 Billion poos in loos.

>Using FFI with C++
extern "C" and don't throw any exceptions. That's all you need to do.

Lisp Machines? I guess writing a C compiler in MacLisp wouldn't exactly be out of the realm of possibility.

Meh, it might hit me why macros are useful if I do something bigger than just an IRC-bot in Racket desu. Racket has been the comfiest language by far to make IRC-bots in desu

C doesn't "run"

because his compiler implemented it that way

What about any of the C++ types (basically anything that isn't a primitive) that should be modifiable?
What about templates or anything which requires name mangling?
At least with C, you get the well-defined struct layout. I know C++ is supposed to have the same layout, but there there is shit like hidden vtables.

The human brain

Yes, you're right, they're different (but not copletely, check the meaning of this word), but the reason I brought it up is because it has similar traits to C, like manual memory management, which I focused on with my argument, and which I value, as I started coding with C++.

>I don't have audio files
>I also, apparently, don't have a way to play and pause. I have a way to play and stop
are you trolling, being dumb, or trying to get me do your homework?
do you know there is some thing web search thing called google that can help you a lot?

Don't all compilers implement it the same?

JIT implies interpretation of the bytecode on some level. I agree that it's (at least in most JVMs) not a "classic" interpreter that reads some instruction and executes it, but in order to be compiled, some program must understand what the bytecode means--i.e. it interprets the bytecode.

>extern "C"

No. Language standard gives them free hand. The order of evaluation of arguments is unspecified.

>there are "people" that think that interpreted language are worse than non-interpreted

By process of elimination: the middle one.

I didn't ask for your help. All i did was write a post on what i'm working on and my experience with that.

well, that's shit isn't it?

Fuck you

But they are worse.

In the Racket style guide there's, like, a thing that says you should prefer procedures over macros because you can do things with functions that you can't with macros (like, how macros behave, rather than there being a limitation on what macros can do)

runtime errors are fun, bruv

The Haskell Exchange, previously known as the Haskell Hackathon will be held October 21-23, 2016 at the University of Pennsylvania in Philadelphia.
Capes, comfortable footwear and beards welcome.

London 6th/7th october

>£650

Premise: I have some input which can be one of a range of possible strings, lets say strings A through E. I'm going to replace these with a prettier version for printing some output later, according to an irregular mapping. e.g. A->Ayy, B->Bee, etc.

Question: What's the cleanest/best practice way to do this? I can think of a lot of implementations but it seems like the obvious best option is to have an array of key/value pairs like

"A: Ayy", "B: Bee", etc.

Then for every input traverse the array and compare the input to the characters before the colon, if I get a match then print the characters after ": ".

Is there a simpler/cleaner way to deal with this? Like a data structure that's explicitly designed for this arbitrary key / arbitrary value scenario.

This is in C++ btw, but I would happy with Java and Javascript answers too.

No, allows for potentially better performance.

And yet C++ doesn't even have restrict in the standard.

SDL is [spoiler]fun, and so is C.[/spoiler]

No a simple lookup table (std::map) will do.

That'd be like this in Python:
lut = {
'A': 'Ayy',
'B': 'Bee',
}

usr_in = input()
print(', '.join('{}: {}'.format(v, lut.get(v)) for v in usr_in))

> A: Ayy, B: Bee, C: None, E: None, D: None, A: Ayy

Use a map (C++ and Java)
in javascript use an object
then simply:
C++: mymap.at(mystring)
Java: mymap.get(mystring)
Javascript: mymap[mystring]

Holy shit proramming is fun

restrict is not very useful. Compilers auto vectorization is still not good enough so when you really need performance you have to reach for intrinsics or assembly, and there restrict makes no difference.

But there must be something wrong with a standard that allows same code to give different results.

Because surely
std::cout

This is perfect! Thank you both.

Beginner. Still going through SICP. Currently on page 54.
Exercises are slowing me down considerably.
I probably shouldn't be using it as bedtime reading.

Are the exercises supposed to be done on a computer or on paper?
So far, I've been lying in bed with pencil and paper, writing and solving the exercises with pseudo-python, but exercise 1.22 explicitly instructed me to run it on a computer.

from time import time

#===From pg54===#

def timedPrimeTest(n, noptf):
startPrimeTest(n, time(), noptf)

def startPrimeTest(n, startTime, noptf):
if isPrime(n):
noptf[0] = noptf[0] - 1
print(n)
print(' *** ')
print(time() - startTime)
print()

#===From pg50===#

def findDivisor(n, testDivisor):
while testDivisor*testDivisor < n:
if n%testDivisor==0:
return testDivisor
else:
testDivisor = testDivisor+1
return n

def isPrime(n):
return n == findDivisor(n, 2)

#=Exercise 1.22=#

def searchForPrimes(startNumber, numberOfPrimesToFind):

noptf = [numberOfPrimesToFind]

if startNumber%2==0:
startNumber = startNumber + 1

while noptf[0]>0:
timedPrimeTest(startNumber, noptf)
startNumber = startNumber + 1


It's supposed to show that, as you increase startNumber by an order of magnitude, the time it takes to compute increases by square-root of 10 (roughly a factor of 3).
I'm assuming I'll have to rewrite it for C++ if I want to show that; Python's showing a consistent 8ms per prime number (excluding the first one calculated, which takes markedly longer to compute).

>restrict is not very useful
Clearly it is, or the major compilers wouldn't have all implemented it. C++ de facto has restrict, it's just not standardized.

try bigger numbers

>Clearly it is,
It's not. hardly any code uses it, and if you look at highly optimized code you will see intrinsics or assembly.
Restrict is just too limited in its usefulness.
But sure, it does help in the few cases where it is useful. and if you design a new language restrict should definitely be the default for every pointer and there should instead be an 'alias' keyword for when you need aliasing.
>or the major compilers wouldn't have all implemented it.
Languages and compilers come up with and implement a bunch of nonsensical shit all the time.

>programming on paper
Just don't do that, and don't listen to anyone who says it's a good exercise

lying is a sin

Not bein a jerk but thats like the lamest gif ive seen in forever.

Legal syntax doesn't necessitate deterministic output (well of course it is deterministic at the end of the day on a particular computer/compiler, but from a standard pov).

You don't write code on paper you idiot

>lying in bed with pencil and paper, writing and solving the exercises with pseudo-python

>hardly any code uses it
It's not fucking standardized and requires compiler-specific annotations. Of course it's not going to see as much use as it would were it standard.

Do it in Lisp.

I meant even in C code bases.

Then how did they write Python back in the 1890s?

So should it not be standardized in C?

It is part of standard C (since C99), and yet hardly anyone cares about it since as I said: you still can't trust the compiler to generate good enough code even when you do use it.

The shit thing that really bothers me about C++ is adopting C standard library changes for their C compatibility but not doing a single thing about adopting any of C's syntax changes since C89.

Why even keep C compatibility in that case? Just fucking ensure you have a way to link to C and then strip the C preprocessor and C-like syntax that doesn't make sense in modern C++ out. If people want to still have C compatibility, they can use version switches. It just makes no sense to tout C compatibility or still have it when it isn't useful today.

The whole invisible snafu means that not everyone is writing modern C++ and for me more relevantly, people write shitty C just to be compatible with C++.

Looks like sand art you'd see in a jar

>You can't trust the compiler

More like you can't trust yourself or other people on your development team to write code with restrict pointers that don't alias. Compilers generate great code with restrict qualified pointers.

Hell, even with strict aliasing in C and C++, people can't write code that doesn't break when it is perfectly possible to do so.

Which looks better?
int diff = abs(ctr->o_len[i] - len);
~~~
char *s = &str[j+len];
memmove(s, s+diff, strlen(s+diff) + 1);
/* or */
memmove(&str[j+len], &str[j+len+diff], strlen(&str[j+len+diff]) + 1);

1

>Legal syntax doesn't necessitate deterministic output
Yes it does. Otherwise it's a shit an useless standard. Actually: Otherwise it's not a standard.

rand()

Are you sure you're not a Rust shill?

>Compilers generate great code with restrict qualified pointers.
Nah they don't.
The one obvious thing is that restrict doesn't give any information about is 'stride width' (i.e the length of a vector register) so it has to emit a bunch of tests and extra code to handle left overs in case array length isn't perfectly divisible by the vector length.
And in fact, without restrict the compiler can do the same thing - just emit two versions of a loop, one which assumes to restrict with a test of the pointer addresses and then just jump to the appropriate loop.

So at the end of the day, when you want maximum performance you have to bypass the stupid compilers still.

>... C++ ... C ... C ... C ... C89 ... C ... C ... C ... C ... C++ ... C ... C ... C++ ... C ... C++

>Yes it does
It really doesn't.
There is a difference between something getting parsed by the language's grammar and getting through semantic analysis.

>Yes it does. Otherwise it's a shit an useless standard.
Such a standard would not be possible.

not syntax

>excluding the obvious of course
You really should define 'obvious' in this context.

I'd say a couple of more powerful macro use cases would be DSL creation and introduction of new language constructs.

1, but use a different name than s. Also "s + diff" looks qt-er than "s+diff". Right now you are doing "(s+diff) + 1" which is inconsistent as far as spacing around operators go. It should be (s + diff) + 1 for that reason.

Don't see how that's relevant.

On one of those of course

if only Lisp was pure and had monads

> restrict doesn't give any information about is 'stride width'

That's not its purpose. If you wanted that kind of stuff, you would use intrinsics or assembly.

The only job of restrict is to tell the compiler that for the lifetime of the restrict pointer, only the pointer itself or a value directly derived from it (such as pointer + 1) will be used to access the object to which it points. That's it.

There's a lot of stuff you can assume from that but the optimizations you want aren't covered from such an assumption.

Which wrote code on... what?

>SICP in python
>coding on paper
STOP

Linear types are better than encapsulation behind monads for controlling side effects and making code pure.

Is there a snake inside of it?

literally nothing wrong with python

56813898
Not having this discussion again.
Every time you end up realising they don't do what monads do, but every time you shill.

the witch's cult attacked their village when they were children and broke her horn off. she and her sister were then adopted by a clown and she became his sex toy

>That's not its purpose.
I know, that's why it's so limited and ultimately pointless.
restrics only real power comes when you loop over two or more arrays, and then what you want from it is to assume no aliasing so it can hopefully vectorize them, but it doesn't have all the information necessary for really good vectorization so it falls short anyway.
In non-loop situations where you have multiple pointers and you don't want the compiler to generate extra lods/stores you can work around it with better code (usually cleaner code even, i.e load the pointer once into a local variable, use it through the function, then store at the end instead of using *p everywhere)

except everything

what's aliasing?

>not writing pseudo code on paper

I added a qualifier. I understand that monads are good for other things. Why are you mad?

damn it, you got me

How old are you?

>writing pseudocode
>for any purpose except to quickly explain something to someone else

I use it sometimes to visualize difficult algorithms

It's not pure if it does side effects, and it doesn't give nearly the benefits monads would.

You could always have both, anyway.

Two or more pointers referring to the same object in memory.

Trying to figure out regex to recognize string for my game. Needs to recognize strings like "

30.

Maybe if you just coding lame business logic.

restrict was never an auto-vectorization hint. Read the C99 rationale.

>The problem that the restrict qualifier addresses is that potential aliasing can inhibit optimizations. Specifically, if a translator cannot determine that two different pointers are being used to reference different objects, then it cannot apply optimizations such as maintaining the values of the objects in registers rather than in memory, or reordering loads and stores of these values. This problem can have a significant effect on a program that, for example, performs arithmetic calculations on large arrays of numbers. The effect can be measured by comparing a program that uses pointers with a similar program that uses file scope arrays (or with a similar Fortran program). The array version can run faster by a factor of ten or more on a system with vector processors. Where such large performance gains are possible, implementations have of course offered their own solutions, usually in the form of compiler directives that specify particular optimizations. Differences in the spelling, scope, and precise meaning of these directives have made them troublesome to use in a program that must run on many different systems. This was the motivation for a standard solution.

std.dkuug.dk/JTC1/SC22/WG14/www/C99RationaleV5.10.pdf

It was only ever intended as a way for memory optimization to take place for pointers. Nowhere does it state or imply vectorization as a requirement. For what it does and implies, restrict does a fine job.

>It's not pure if it does side effects
Side effects can be fine. It's when they're observable that you run into problems. You can make them non-observable with monads, and you can make them non-observable with linear types. Linear types are simply better at that task.

>You could always have both, anyway.
I'm not arguing against this.

>Confirmed for messy code

WHY IS MY POLYGON ROTATION NOT WORKING
private double currentAngle(Point2D point, double dist) {
System.out.println(Math.asin((point.y - center.y)/ dist)*180/Math.PI);
return Math.asin((point.y - center.y)/ dist);
}

public void rotate(double degrees) {
degrees *= Math.PI/180 ;
for(Point2D point: points) {
double dist = Math.pow(Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.y, 2), 0.5);
point.y = (Math.sin(currentAngle(point, dist) + degrees) * dist) + center.y;
point.x = Math.pow((dist*dist) - Math.pow(point.y - center.y, 2), 0.5) + center.x;
}
}

>Side effects can be fine
But my point is you want to be able to say "no side effects here"
You need monads or an effect system for that
Monads are generally more first class than an effect system

Oh. I thought is was some fancy language construct i wasn't aware of.

Oh, and also to be able to manipulate effectful computations as values, which lets you do stuff like build your own control flow structures, define effects built of effects, etc

So you could say get a line from stdin and then parse it
readLine = read getLine

But without monads:
readLine = read(getLine())
(this is not at all the same thing)

>restrict was never an auto-vectorization hint. Read the C99 rationale.
Yes, I know.
But that's the only real impactful optimization it enables.
Other cases can easily be 'coded around' by doing more explicit loads and stores in your code (which imo is cleaner code).
Show me a non-loop situation where you think restricts help and I will show you a version of the code which achieves identical machine code without using restrict.

And pseudocode helps how? If i write messy code i write messy pseudocode.

New to programming. Started a small project and needed to iterate through a string and push the words into a vector.

So far it works, except it cuts out the last word. Pretty sure this is because my if-statement is looking for a comma at the end where there isn't one. I know I could append a comma at the end and it would just werk, but I wanted to know if there was a null terminating character I could use instead.

If so, I could just include an OR in the if-statement to look for that character, right?

string[string.length - 1] is the last character of the string, not of the c string
So if you wanted to do that, you'd need to do
j

If you think before you act you can definitely form a cleaner program.

Just realized I left the "initStr.length() - 1" inside the if-statement. That was just me testing out a solution which didn't work, it eventually led me to the concept of null termination ithough. Sorry about that.

And this is just for strings, regular vectors and arrays do end at their length - 1

Exactly. Think.

>You need monads or an effect system for that
Or linear types. Check out "Linear Types Can Change the World!" by Philip Wadler.

>you need monads for this
>only uses fmap
In any case, this is where the rest of the utility of monads comes in.

As far as controlling the effects in this example, here's how it might look with linear types (a linear world, to be precise):
readLine world = let (world', line) = getLine world in read line world'

You will probably notice that a state monad would make this cleaner, and you'd be right. IO is just a state monad under the hood, at least in GHC. The linear types make the transformation from impure to pure more precise and more general than forcing it to be in a monad.

>wasting 8 bytes just to something slightly easier to read

How is it not working?

Yep, that is exactly the reason, just push_back after the loop as well.

#include
#include
#include

int main(int, const char **)
{
std::vector words{};
std::string init{"w1,w2,word3,w4,w5"};

std::string current{};
for (const char &ch: init) {
if (ch == ',') {
words.push_back(current);
current.clear();
} else {
current += ch;
}
}
words.push_back(current);

for (const auto &word: words) {
fprintf(stdout, "%s\n", word.c_str());
}
return 0;
}

There's not much point in using a memory optimization hint outside of non-heavy memory accesses aka non-loop situations.

If you wanted to make deeper assumptions about the loads and stores, just use intrinsics and assembly so you can do so.

It helps to visualize your thoughts in pseudo code. And sometimes you can spot some errors or things you didn;t think of until you wrote it.

What would the type look like?

>pencil and paper
because making dozens of mistakes doesn't matter as long as you don't have to debug anything

> break the ice session
> asian kid enters late
> lecturer pounces on him
> "tell us your name and hobby "
> uhhh..Huawei and anime
> "I'm sorry, what is that ?"
> *incomprehensible muttering*
> "say again"
>cartoons
> " take a seat"

Self confidence grew abit after it.

>stupid frogposter
>SICP in python
>uses pencil and paper
>thinks this makes error checking easier
>is correct, but only because he chose Python

getLine :: World -> (World, String)
read :: String -> a
readLine :: World -> (World, a)

World would be a linear type.

Also, I wrote that code wrong because I seem to constantly think that read is IO.
readLine world = let (world', line) = getLine world in (world', read line)

>It helps to visualize your thoughts in code. And sometimes you can spot some errors or things you didn;t think of until you wrote it.

Fixed it for you.

Though if you're designing a solution and don't happen to have a computer by, i guess pseudocode is good enough.

Why would linear types be necessary for this in a pure language?

And wouldn't you need monads anyway so that you aren't constantly required to explicitly pass world?

just because asians grew up watching doraemon doesn't make it normal for a westerner to like anime

The main draw to paper is algorithms and datastructure. It's just infinitely better for planning

One should not be embarrassed by ones hobbies.

But what if you can write something pseudo code 5 times faster than in code?

unless it's anime

They aren't, they're just better. Not for this particular example, but when you start getting into managing individual resources like heap allocations, files, etc. it really shows. Simply trying to do this:
>allocate A
>allocate B
>free A
>free B
while maintaining all of the invariants that prevent various memory errors requires a lot of gymnastics with region monads. It's very straightforward with linear types.

This is what Rust does, for instance. Well, it has affine types, but they're very similar to linear types.

Yes, but now you're just using the monad for abstraction purposes, not abusing the sequential interface to simulate linearity.

But that's before the pseudocode stage. If your idea is well formed enough to write down in code like form, one might as well write it down in code directly.

Ahh, got it. Thanks!

Do uniqueness types do anything for anything other than IO/ST/State style monads?

Then either your code or your pseudocode is shit.

What compilers do you guys use for C++ and Java? Linux/Windows/OSX

No. You own it or you drop it.

I don't advocate for pseudocode in the traditional sense. Graphs with code like notes is pseudocode.

>compiler
>Java

Rich.

Well, they're for resource safety. Some monads are for resource safety (IO, ST) whereas others are pure abstraction (Maybe, Either, State, lists, etc.). Linear types have nothing to do with the latter.

The difference between the two camps is that IO and ST hide their implementation details and only expose a monad interface, whereas the rest are monads by construction. Monads to control side effects are artificial.

Kek didn't mean to put java just C++

>tfw your brain starts doing shit you don't want it to after 30 hours of Cred Forums

Your face is pseudocode.

>explaining research to company recruiters
>offhand reference compiling java programs in process
>do this multiple times
d-did I mess up?

>"im user and my hobby is anime"
>"i'm sorry what is that?"
>"uhhhhh *mumble mumble* japanaese animation"

Maybe/Either/lists also model side effects, just not IO side effects, e.g

do
replicate 2 ()
pure 3


replicate 2 () performs a side effect, the rest of the output is duplicated

and Either can be likened to throwing an exception
maybe is just [] with a max length of 1

Java compiles to byte code.

I don't even know what you wanted to get across by this post.

I'm working on learning C...

How is it going?

How much experience do you have programming already?

Well, I'm enjoying le nerd feeling

any idea why my database (influxdb) that takes
"2009-11-10T23:00:00Z"

won't take
datetime.datetime.now().isoformat()+'Z'

That's great, enthusiasm is pretty important

Just use Clang or GCC on each platform. Visual C++ is getting slowly to being on par but it is still missing some extended templates stuff like 2 phase translation and Expression SNIFAE. Constexpr having some weird quirks is the biggest missing thing in Visual C++ though.

No, not really since people call the Java source code to bytecode translation "compiling" which is technically correct.

However, you don't exactly have a compiler per say since the JVM is doing everything.

Good to hear.

I do it because I go over SICP late at night, last thing before I go to sleep.

Sensible suggestion.
I haven't done so because I found installing the languages I have now such a hassle that... well, I can't be arsed. I've got Java, C++, Python and, push comes to shove, there's always javascript on my browser.

Actually, I use it to better understand the code in the book. And to do the exercises.
When the exercises ask for something to be computed (e.g: smallest-factor(199)), I go through each step on paper, writing out the comparisons made at each if/cond statement crossed, their outcomes and any values that change.
I think the book called it "the substitution method" and definitely helped on the applicative-order/normal-order questions.
Also, I had to debug the code in when going from my 3am pseudo-python-in-bed to "I fudged it a bit but it works" python.

>source code to bytecode translation "compiling" which is technically correct.
>you don't exactly have a compiler per say
Well? Which is it? If it's technically correct that it's compiling, then it's technically correct that you have a compiler. Per se.

They're not side effects. They're entirely pure by construction.

Side effects are when you manipulate "the world". In order to ensure that these side effects are not observable, and thus don't break your reasoning ability, you have to ensure that you only have one world at a time. This is the meaning of the IO monad, but it can be done just as well with linear types. However, you can conceptually break this world into pieces so that you can manipulate separate parts of the world simultaneously. This is where monads start to not really work that well, but linear types scale up to this just fine.

These bedtime coding sessions sound comfy

I'm using C#. Is there a way to run a block of code for just a set period of time?

I want to Print to the console, while accepting readkey(); but I only want to check for the ReadKey(); for a set amount of time before cutting to the next print?

Webm is an example of what I want to fix, right now its just a simple loop that checks for ReadKey(); every update.

It definitely is compiling.

Javac is the compiler from source code to bytecode and JVM runs to interpret the bytecode.

Have you ever used java?
Of course you do have a compiler. It's called javac.

>They're not side effects. They're entirely pure by construction.
No, you call them pure because they can be ran purely.
You could just as easily construct an interaction monad, where there are instructions to read and write lines, and you could run this monad either with IO or in a pure setting.

>Side effects manipulate the world
No

Not that guy but, to interject, you can think of it as Java having both a compiler and an interpreter: a Java compiler compiles the code into bytecode when can then be read by the virtual machine on any device.
So you've got both. You're not wrong but there's more to it than just compiling.

Hmm, Pretty shit since my computer here is used by kids too. But I'm trying hard since I heard you can do almost everything in C.

I'm a noob, know some basic things but C is my first time learning a programming language.

Similarly in the list example, it could be run impurely with even something like a fork() (and then some kind of yield)

You could write your own Unix monad that would behave exactly like IO, except that as well as running it in IO you could run it on a pure emulator.

>never used java before
>only know c/c++/lisp
>taking mandatory java course for college
>java just works
>don't have to fiddle with things like i always seem to end up having to do with other languages


i'm starting to enjoy java

is this bad

They sound excruciatingly slow and annoying.

Wouldn't most JVMs be a hybrid since it interprets and compiles?

I never said computers couldn't run programs written in C. Reread my post.

Just don't try and do everything in C

I know. So?

Nevermind I figured it out I think.

>and you could run this monad either with IO or in a pure setting.
>IO
Exactly.

What is a side effect to you? Remember that the important thing is that we maintain purity, which is that the same inputs always give the same outputs. So that just means no observable side effects.

>it could be run impurely
It wouldn't be impure, though. And that's still different from discerning a monad instance from a list.

Thanks, i know this.

>3 Billion Devices
Not really, if it does what you want. I felt the same way about Ruby.

Nope it's perfectly fine. You're gonna have a harder time on Cred Forums though.

I feel like your mind has been warped by Haskell's laziness so that you can't tell the difference between actually running an operation that affects the world and constructing a free monad that might be interpreted to do that at some point.

If you look at the computation, the result can be different.
Thinking of the list monad - it has many results, all of which can be different results.
(LITERAL non-determinism.)

And when I said the interaction could be run either with IO or in a pure setting, I meant you could do either
You could
A) Feed it a known list of inputs, produce a list of outputs and a result
B) Literally run it on the console
But it's the SAME computation.
The side effects are reading a line and writing a line.

I kind of liked java in the beginning too.
Then i went on to c++ and when i return to java it was disgusting.

>warped by Haskell's laziness
Non-termination and performance/memory are the only potential problems with laziness.

This has nothing to do with controlling side effects any more. You're just trying to school me on free monads, algebraic effects, etc. If, in the end, these reified computations are going to be run and affect the world, you want to have some way of proving that they are not going to do it in a way that will destroy your reasoning of the rest of the programming. And then we're back where we started.

idk

it could be that with java doing things I already know how to do in other languages is just easier since i understand the concept already

Those ARE side effects and it is important to reason about them.

What are?

"Get a line, put a line"

The rest is completely abstract

what can I do with lisp?

At some point, you want to be able to say specifically "get a line from stdin". This is goalpost-moving of the highest degree, because that's what getLine means.

I didn't say from stdin
I didn't even say it involved IO

This isn't goalpost moving at all. I said exactly what I meant. I want to create a type of effect where you can get a string, or put a string. The rest is entirely abstract.
The fact I can run it in IO, or with a list, or with state, is besides the point. Those are just monad homomorphisms.

New programmer, just wondering why do people bash C++ iostreams on Cred Forums what precisely makes them shit?

>I didn't say from stdin
>So you could say get a line from stdin and then parse it
>get a line from stdin
>getLine

Pic related as an example.
These are meaningful abstractions defined simply in terms of the put and get (not to be confused with set and get) effects.

>COULD
I've said this three or 4 times, you could run the same computation in a pure environment

It's getting me through the book.
It's how I got through beginner Java and C++ books after not having touched a book in some half a dozen years.

Well the original point was that linear types are better than monads at controlling side effects and none of this shit you're saying now has anything to do with that, not that I disagree.

The original point wasn't that at all
I said "If only lisp was pure and had monads"

YOU brought up linear types AGAIN
and this is the THIRD TIME you've tried to end the conversation with >not the point
That was EXACTLY the point

Well, sure, if it was pure as in it couldn't do any side effects at all in any way, you wouldn't need linear types. But it would also be useless.

Do you guys have multiple accounts on GitHub, or whatever else you use. For the kinds of stuff you don't want to associate with in your public life?

It's an overengineered complex mess to use, compare to cstdio

What are you even talking about?
Are you just completely confused in your ongoing attempt to make linear types relevant?

>Do you guys have multiple accounts on GitHub, or whatever else you use. For the kinds of stuff you don't want to associate with in your public life?
Of course.

How are they not relevant?

They don't provide the benefits that were the point of mentioning monads for lisp in the first place. (first class effects)

You said "pure and had monads" and clearly you need some way to make it pure. Haskell is pure with monads and it uses monads to make itself pure. What were you going for?

I haven't disagreed with you on the myriad other uses for monads (and not just monads at that) and instead of backing up your claims that I'm wrong about linear types you just keep reiterating the other things I already agree with. If you're not going to bother trying to prove me wrong, we can stop.

I'm not prolific enough to do that.
That's the sign of a workaholic.

What are you talking about?
I said "if only it were pure and had monads".
Your bringing up linear types has never, at all, been relevant. You have done this not once, but on three seperate occasions. You will do this probably at least 2 more times.

You could have just said it's irrelevant. Instead you said I was wrong.

>You could have just said it's irrelevant. Instead you said I was wrong.

> they don't do what monads do

>It's not pure if it does side effects, and it doesn't give nearly the benefits monads would

read sedgewick all day i'm considering suicide

That's right, it's not pure if it does effects

>>it doesn't give nearly the benefits monads would
That sounds awfully a lot like what you wanted me to have said

They're slow.
They're ugly.
They're verbose.
They hurt internationalisation by hard-coding the order of the arguments.
C's stdio is better in every way.

Compare
#include
#include

int main()
{
std::cout

>%-10.3f%s\n
desu

How is it a sign of a workaholic?

>That's right, it's not pure if it does effects
So it's useless. Nice.

>That sounds awfully a lot like what you wanted me to have said
If you thought I was somehow baiting you, why did you reply? Could have just stopped while you were ahead and instead you ended up saying a lot of things while getting nowhere in your apparent crusade against linear types.

>So it's useless. Nice.
No, it could return an effectful program.

And then how do you know that that effectful program is safe?

I also forgot to mention the brilliance that will happen if an exception happens between modifying the stream and resetting it.

>>LINEAR TYPES ARE SO MUCH BETTER any time anyone recommends monads as a language feature
>respond
>>crusade against linear types.

Define safe
You've got all the safety of Haskell in Haskell, you can think of SafeHaskell (or standard haskell which doesn't have unsafePerform) as working this way.

by SafeHaskell I'm not referring to the discussion of safety btw, I mean the extension to GHC that bans unsafePerform (and some other stuff), unsafePerform isn't even part of standard haskell 2010

I lied I didn't find an answer.

I have no idea how to solve this.

>They hurt internationalisation by hard-coding the order of the arguments.
what?

>You've got all the safety of Haskell in Haskell
Which would be better with linear types.

>standard haskell which doesn't have unsafePerform
Which means you're back to the one world scenario where, while linear types are no better than just using the IO monad, you can't perform any side effects in parallel.

>Which would be better with linear types.
I don't see what benefit they provide over IO.

>you can't perform any side effects in parallel
Yes you can. The language just has to expose some kind of primitive fork or parrallel.

In fact, using the Parallel library, you can define

instance MonadZip IO where
mzip = concurrently


And use MonadComprehensions and ParallelListComp to get

[ a + b + c | a

I don't think i understand what you want. You want to check ReadKey() only a limited number of frames?

>I don't see what benefit they provide over IO.
Resource safety, like in Rust.

>The language just has to expose some kind of primitive fork or parrallel.
But how do you know that it's safe to run any IO operation in parallel?

It's harder than you think. You have two problems in one here.

First one is to split input and output by using threads, otherwise they can't happen at the same time. So you have one thread printing stuff and the other is doing ReadKey();
You should probably use cancelable background workers, see here: msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

Second problem is making a ReadKey(); that times out. You could look here for inspiration:
stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline

Anyway this probably amounts to too much work for what you are trying to do, I'd recommend architecting a different program structure if you can, so as to avoid both of those problems.

>Resource safety, like in Rust.
Not impossible, but I don't think you could achieve this easily without dependent types (obviously or linear types)

>how do you know it's safe
Define safe

>Not impossible
It's certainly not impossible to achieve the same safety with monads as you can with linear types, but it's horribly painful and verbose.

>Define safe
No bugs.

Say you're writing a program that will print the name of some object and what colour it is.
For example: "a red balloon".
#include

int main()
{
std::string article = "a"
std::string object = "balloon";
std::string colour = "red";

std::cout

Well, no bugs that arise from incorrectly using the OS/hardware.

Logical errors are another thing entirely.

>it's horribly painful and verbose.
No it isn't

>No bugs.
A language that achieves that would be horribly painful and verbose. It would be dependently typed, and linear types would be the least of your worries.

>First one is to split input and output by using threads
If he's making a a games, as his webm suggests, he's going to have to do that anyway.

Except, game + C# suggests Unity, in which case what's he doing mucking about with ReadKey?

That's completely irrelevant to anything, you'd never do either those things in production. You would store the strings "a red balloon" and "un ballon rouge" and then cout the entire string, depending on what language the user has selected. The reason is, most of the time you can't just trade out the words and expect the translation to make sense.

But all you're doing is building strings. Only real advantage to describing your grammar with a string is easy command line argument scripting and such.

Does anybody know how Cred Forums links to posts in other threads? Is there a way to find out the contents of a post without having to load the entire thread? I wonder how the Cred Forums native extension does it.
Test.

This shit even applies if you're only a single word is a variable.
std::string name = "Christopher Poole";
std::cout

>std::
>::

Boost Format

So format strings. Exactly what I was arguing for.
Also
>boost

With linear types (the definition of Ptr a as linear means no machinery):
new :: Ptr a
free :: Ptr a -> ()
read :: Ptr a -> (Ptr a, a)
write :: a -> Ptr a -> Ptr a

test :: ()
test = let a = new in
let b = new in
let () = free a in
free b


Without (you need indexed monads and indexed monad transformers):
data NotFreed
data Freed
newtype Mem s i j a = Mem { runMem :: IO a }

instance IxMonad (Mem s) where
ireturn = Mem . return
ibind ma k = Mem $ runMem ma >>= runMem . k

withNew :: Mem NotFreed Freed a -> a
free :: Mem s NotFreed Freed ()
read :: Mem s NotFreed NotFreed s
write :: s -> Mem s NotFreed NotFreed ()

I don't even want to try to write test. You also can't refer to resources by name, it's all about their place in the monad (transformer) stack. Unless you want to add regions...just to refer to them by name.

new

I wouldn't bother with that, if I wanted manual memory I'd do manual memory, not "sort of manual but sort of not"

#include

int main()
{
std::string article = "a"
std::string object = "balloon";
std::string colour = "red";
int format[] = {1,2,3};

std::string lex[] = {article, object, colour};

std::cout

>So format strings. Exactly what I was arguing for.

Yes.

>>boost

Might as well be part of the standard library.

What are your thoughts about Pharo Smalltalk?
I think it is a very interesting language and platform, making the language and the ide one and the same.
Also, the debugger is a work of magic.

After checking, it looks like they load the entire thread. Bummer.

wait, what
teach me how to pointers in haskell

hackage.haskell.org/package/base-4.9.0.0/docs/Foreign.html

So if I crosslink lots of big threads I can punish mobile users?

I'm making a console application game. I don't know its probably not worth fucking about with two threads to have retarded console animations. Still frame ASCII art with text would probably work fine for cut-scenes if executed well. I mean I got non-blinky animations working with a double buffered text output but making them non-skippable was the problem.

I meant making them skippable, not non-skippable.

It only loads them when you hover. And it times out in 2 seconds.

>format[3]
>3
?

Yeah alright. I fucked up. You know what i meant.

I think the only way to make this efficient would be if Cred Forums had some kind of REST api to spit out only the requested post.

Yeah, that's what I was looking for. I looked in the JSON API, but you can only see full threads, so I wanted to see if the extension used some undocumented API.

yeah true

i agree with you about printf. is there a type safe C++ equivalent to printf without having to roll my own every fucking time?

Printf isn't type safe?

You don't roll your own every fucking time. You do it once, to suit your typical use cases, and make a lib of it.