Programming thread

Does someone know how I can use the MediaWiki software to create an offline wiki for my own writings?

I recommend just writing your stuff using Markdown, you can convert them into a web site with quite a few tools at any time.

 
C++ is bloated af and I pity the ones who have to rely on it. It compiles slow, has a thousand and one gotchas, and does not offer anything over plain old C. I write elegant, hobby programs in C and that's so much smoother than swimming in STL vomit. It's also easier to learn because there's less cognitive load. Sure, you can monkey-train yourself into writing working C++ and I've done that, but that's due to the absolute state of the world, not to the inherent qualities of C++.
Destructors are nice, and making up (simple) classes is nice. That is, compared to how you'd implement them in C.
But I agree about the bloat. If you show me something with multiple inheritance, template """wizardry""", lambdas (which I can't believe are part of the language now), friend classes, those weird first-generation "almost-smart" pointers, etc. you better bring your fireproof clothes.
You cavemen clearly have not tried exploring the potential of templating. At it's most basic it lets you create a convenient list type like std::vector, at it's most complex it lets you create an entire interface system of your own design.
Lambdas are basically just a shorthand for functors, and they can now pretty much anything a function can do including nutty shit like this;
C++:
// Prints the contents of an arbitrary tuple type
template<typename TTuple>
void PrintTuple(std::ostream& stream, TTuple&& tuple) {
    // Determine the number of elements in the tuple
    constexpr size_t count = std::tuple_size_v<TTuple>;
    stream << "("; // Print the opening bracket
    if constexpr (count > 0) {
        stream << std::get<0>(tuple); // Print the first element with no comma
        [&]<size_t first, size_t... i>(std::index_sequence<first, i...>) { // Lambda with template parameter pack containing the indicies of the tuple
            // Note that index `first` is ignored, this is because we printed the first item separately
            ((stream << ", " << std::get<i>(tuple)), ...); // Print the remaining contents with a parameter pack comma fold
        }(std::make_index_sequence<count>()); // Call the lambda with an index sequence to deduce the tuple indicies
    }
    stream << ")";
}
This code uses the stl tuple interface to print the members of an arbitrary tuple type, separated by comma, between two parentheses. While it in and of itself is obnoxiously verbose, it's use is as simple as PrintTuple(std::cout, myTuple) for every tuple type, and it adds no overhead to the manual implementation. The benefit is that you don't have to constantly restate yourself, you can write this function out once, and then use it many times, for many different cases.

C++:
// Rough tuple implementation, done from memory

// Forward declaration of general form
template<typename... T>
struct tuple;

// Single element specialization
template<typename TCur>
struct tuple<TCur>
{
private:
    // Specifies type of tuple element
    template<size_t i>
    struct element_t_
    { }; // Default case has no type
 
    // Specifies this type
    template<>
    struct element_t_<0>
    {
        using type = TCur;
    };
public:
    // Get the type of element at index i
    template<size_t i>
    using element_t = typename element_t_<i>::type;
private:
    TCur value_;
public:
    // Get the element at index i
    template<size_t i>
    constexpr TCur& get() {
        static_assert(i == 0, "index out of range");
        return value_;
    }
 
    template<size_t i>
    constexpr const TCur& get() const {
        static_assert(i == 0, "index out of range");
        return value_;
    }
 
    // Forward a single arbitrary argument to the inner value
    template<typename TArg>
    constexpr tuple(TArg&& arg)
        : value_(std::forward<TArg>(arg)) {}
     
    constexpr tuple()
        : value_() {}
};

// Multiple element specialization, recursively derives itself
// Note that the elements are stored in reverse order in memory, this can be fixed semi-easily, but this is omitted for brevity
template<typename TCur, typename... TRemaining>
struct tuple<TCur, TRemaining...> : tuple<TRemaining...>
{
private:
    using NextTuple = tuple<TRemaining...>;
public:
    // Get the type of element at index i, delegates non-zero i to the next tuple
    template<size_t i>
    using element_t = typename std::conditional_t<i == 0, TCur, typename NextTuple::element_t<i - 1>>;
private:
    TCur value_;
public:
    // Get the element at index i, delegates any non-zero i to the next tuple
    template<size_t i>
    constexpr element_t<i>& get() {
        if constexpr (i == 0) { // constexpr if; branches at compile time
            return value_;
        } else {
            return this->NextTuple::get<i - 1>();
        }
    }
 
    template<size_t i>
    constexpr const element_t<i>& get() const {
        if constexpr (i == 0) {
            return value_;
        } else {
            return this->NextTuple::get<i - 1>();
        }
    }
 
    // N-argument constructor, passes remaining arguments to next tuple
    template<typename TArg, typename... TRemaining>
    constexpr tuple(TArg&& arg, TRemaining&&... remaining)
        : NextTuple(std::forward<TRemaining>(remaining)...), value_(std::forward<TArg>(arg)) {}
  
    // Single argument constructor, allows arguments to be defaulted
    template<typename TArg>
    constexpr tuple(TArg&& arg)
        : NextTuple(), value_(std::forward<TArg>(arg)) {}
     
    constexpr tuple()
        : NextTuple(), value_() {}
};

// Standard tuple interface implementation
namespace std
{
    // Forward declared to avoid need for inclusion of stl tuple
    template<typename TTuple>
    struct tuple_size;
    template<typename... TArgs>
    struct tuple_size<tuple<TArgs...>> : public std::integral_constant<size_t, sizeof...(TArgs)>
    { };
 
    template<size_t i, typename TTuple>
    struct tuple_element;
    template<size_t i, typename... TArgs>
    struct tuple_element<i, tuple<TArgs...>>
    {
        using type = typename tuple<TArgs...>::element_t<i>;
    };

    template<size_t i, typename... TArgs>
    auto& get(tuple<TArgs...>& tuple) {
        return tuple.get<i>();
    }

    template<size_t i, typename... TArgs>
    const auto& get(const tuple<TArgs...>& tuple) {
        return tuple.get<i>();
    }
 
    // By defining these types and functions this tuple type will be able to be used in generic algorithms just as std::tuple would
    // In addition tuple-like types like std::pair also implement this interface, and as such can use the same algorithms
    // This is the true benefit C++ brings; genericness of algorithms.
}
A tuple type may be "unnecessary", but consider the alternative; innumerable single use struct types. Each of these types will need to be defined separately, and will entail a ton of boilerplate code. For the common case of returning a couple values a generic type is much more manageable. Eventually you will even get comfortable with templating's rules and then even stl code becomes legible.

While there is no denying C++ is a mess, consider how it has grown; a new feature is added, and then it is discovered that the new feature has implications, or unplanned uses. Consider the humble type requirement;
C++:
// SFINAE chooses this function for T which are Plain-Old-Data
template<typename T,
    std::enable_if_t<std::is_pod_v<T>, int> = 0>
void copy(T* dst, T* src, size_t count) {
    std::memcpy(dst, src, count * sizeof(T));
}

// SFINAE chooses this function for T which are not Plain-Old-Data
template<typename T,
    std::enable_if_t<!std::is_pod_v<T>, int> = 0>
void copy(T* dst, T* src, size_t count) {
    for (size_t i = 0; i < count; i++) {
        dst[i] = src[i];
    }
}
std::enable_if_t<std::is_pod_v<T>, int> = 0 is the constraint, while std::is_pod_v<T> is the condition
This works by creating a template argument of type std::enable_if_t<...> with the default value 0
If the condition std::is_pod_v<T> is true, enable_if_t<...> reduces to type int, which goes unused
If the condition was false, enable_if_t<...> produces a type lookup error
When deducing template arguments, a lookup error simply disqualifies the templated function, and the deducer moves on
As a result of all of this nonsense, the correct function is chosen by a process of elimination

An important note is that enable_if_t is written in pure C++, it is an emergent feature of C++, not some kind of standard library fuckery
Now honestly, could this absurdity have possibly been a planned feature when they were designing the templating system? Hopefully not, god save us if they actually thought of this and thought it was pleasant to use, and yet it is quite useful. With it you can make intelligent functions that are picked by the compiler based on any arbitrary compile time constraint. Soon enough C++ will receive a formal way to do this in the form of constraints, which will make this functionality all the more accessible.

C is elegant by it's nature of providing just enough to be a good cross platform upgrade from assembly, but it lacks any ability to have it's language features extended. Preprocessor macros are not an argument, they are far worse than anything templating brings. C++ on the other hand, can be made to do all kinds of wonderful and mad things, and in the end is just a powerful macroing system for C.
 
Last edited:
C++ is bloated af
I don't understand this argument at all. Nobody is forcing you to use components of the standard library that you don't need/want.
does not offer anything over plain old C
Thread cancellation
Waiting and signaling on atomics
RAII
Operator overloads
std::atomic_ref
constexpr
static_assert
Soon enough C++ will receive a formal way to do this in the form of constraints, which will make this functionality all the more accessible.
I rarely need to write template functions, but I'm really looking forward to constraints. They'll make it much easier to decipher compiler errors
 
Nobody is forcing you to use components of the standard library that you don't need/want.
This is true as long as you're the only one coding, or if you're in charge. But in an organization you're at the mercy of the single most gee-whiz "Guess What I Just Read On The Internet" person who can manage to get their code checked in.
That could be said of any language of course, but C++ does have a lot of stuff I'd hate to debug.
 
I don't understand this argument at all. Nobody is forcing you to use components of the standard library that you don't need/want.

Thread cancellation
Waiting and signaling on atomics
RAII
Operator overloads
std::atomic_ref
constexpr
static_assert

I rarely need to write template functions, but I'm really looking forward to constraints. They'll make it much easier to decipher compiler errors
Yeah, templating errors are the worst. You can now design templates defensively with static_asserts at least, but the stl doesn't and it'd be pretty verbose too.

Also I hadn't looked into atomic_ref before, but it looks pretty much like what I wanted. One thing I've always hated about std::atomic is that you have to annotate your atomic members with it, meaning atomic has to be included in your header file. I've always wanted to just put atomic in the definition file as to not clutter the header with dependencies.
Interesting to note that a monitor pattern is common for non-trivial atomics. I've been thinking of making a system like this for my language being that a lot of handle types in it are bigger than 8 bytes.
 
Now honestly, could this absurdity have possibly been a planned feature when they were designing the templating system? Hopefully not, god save us if they actually thought of this and thought it was pleasant to use, and yet it is quite useful.

My father was fascinated by the concept of compile-time primes after reading about it because he was certain that, and I'll lay it out in his way of thinking, The Creator went from being the architect of reality to a curious observer of his own creation.


I have been meaning to get back into programming for a while after a break of many years. The thinking is still there and I still remember how things work on a high level, but an inch deeper than that and it becomes an endless ocean of hazy memory and frustration when I trip over things I know I've done wrong but I don't remember why. Is there something like Duolingo for programming languages? I'm not going try to program on a smartphone but an endless torrent of multiple choice questions as it relates to snippets of code for a specific language on a device like that would be wonderful.
 
  • Like
Reactions: Strange Looking Dog
Idk if it’s offtopic or not, but can you say something about Undemy programming courses? Can you recommend this platform?
I finished C# courses on different platform and now I want to move forward, and Undemy has a beginner machine learning course for a sweet price.
 
I've been doing a client project recently which involved a good deal of reworking some client-side JavaScript stuff, and in particular implementing some libraries and tweaking their behavior to match what my client is looking for. It's so frustrating.

First off, there's just the whole lack of OOP. What do you do if you're coding in an OOP language and the library you're using does maybe 98% of what you need it to do? Oh, you just subclass the class which has the part you want to change, override a property or method or two, and use that instead (presuming the library authors weren't jackasses who abused final). But in JavaScript libraries, there's no OOP so there's no subclassing, and there's a pretty good chance the authors have done something obnoxious like wrap the whole damn thing in JS's weird giant closures anyway, so you can't even do the foo._bar = foo.bar; foo.bar = function() { foo._bar(); //other stuff }; hack. Now another solution could be to just fork the code and hack it and then just use my private fork, but see below.

Second, Node.js has so taken over the JS ecosystem that I think JS library authors have forgotten that there are people out there who are still only interested in using their code client-side. Instructions will generally start with an npm command, and code samples will start with a few require() calls. Instructions relevant to client-side use are often included as a seeming afterthought if they're included at all, so sometimes I have to try to "port" the Node instructions and code to something I can actually use. It's frustrating. And as it turns out, the "dist" files for client-side use have been transpiled from the Node code, so I can't even tweak the code without installing Node.js and then learning how to code in it, which I'd rather not do. Now this wouldn't be so much of a problem if I were just able to subclass the parts I wanted to change and be able to tweak them with my own standard client-side coding style, but see above.

Bah. Maybe I'm just stubborn for not wanting to get on board with the new Node-centric ecosystem. But I just need to tweak a couple minor things with how the existing code works, aand that shouldn't involve an entirely new runtime and transpiler and superset of the language.
 
Last edited:
This is true as long as you're the only one coding, or if you're in charge. But in an organization you're at the mercy of the single most gee-whiz "Guess What I Just Read On The Internet" person who can manage to get their code checked in.
That could be said of any language of course, but C++ does have a lot of stuff I'd hate to debug.
I once wrecked a system that got hit over a million times a day because of a nuget package reference.
 
How much math do you have to know to be a programmer? I've heard you've gotta know shit like trig to work in C.
 
How much math do you have to know to be a programmer? I've heard you've gotta know shit like trig to work in C.
You don't have to know any, and you don't need trigonometry to write C code. But for a lot of interesting things you'd want your program to be able to do, knowing a bit of mathematics helps. And the problem-solving process is (supposed to be*) mostly the same between mathematics and programming anyway; thinking 'mathematically' helps you write programs, and thinking 'computationally' helps you grapple with math.

*Supposed to be. I've found this to be true for myself, and lots of programmers I know are also good at math and have little difficulty picking up mathematical concepts. However for reasons I cannot fathom, it doesn't seem to work vice versa. I've seen people with PhDs in mathematics and statistics struggle with the concept of functions and parameters. So your mileage may vary, I guess?

Anyway, better people than I in this thread have said their piece about mathematics and programming before, so I'll shamelessly plagiarize their answers too:
I'm primarily a web developer who also does some simple desktop and mobile stuff, and I almost never have use for mathematics outside of basic algebra and the concepts of modulus (not sure if that counts as algebra). Plus, of course, logic, if you count that as math. Sometimes I have to do geometry like the Pythagorean theorem, but that's maybe once a decade.

Granted, if you're going to be making games, you're probably going to be doing some trigonometry. Polygonal graphics and even 2D graphics tricks like sprite rotation is all trig. But for the most part, I'd say that you can get away with just a command of high-school-level math.
The only time I've needed to learn any real math is dealing with gamedev stuff. Shaders, physics and 3D rendering.
That's not to say there isn't a lot of math that's really fucking useful, but it's usually either domain specific stuff like coordinate transformations for a physics engine or things that you'll learn in a computer science context and use all the time, like group theory or graph theory.
Also math, math, math. Shockingly big amount of "programmers" that are on a barely-highschool math level. (and below) Many will tell you you don't need to be good at math to be a programmer and I guess that's true but if you aren't you'll always be very mediocre, believe me, that is also true.
 
How much math do you have to know to be a programmer?
If you're actually designing or analyzing algorithms, the branch of mathematics called discrete mathematics will be essential.
This book has a good selection of relevant topics: https://www.amazon.com/dp/1337694193

But most of the time you're probably not designing or analyzing algorithms. In ordinary work I'd say it's more about knowing to ask the right mathematical questions, whose answers will usually be simple arithmetic. "Can this variable overflow?" "How much memory will this take if we have X data points?" "How many iterations are we talking about here?" Things like that.
 
How much math do you have to know to be a programmer? I've heard you've gotta know shit like trig to work in C.
If you're actually designing or analyzing algorithms, the branch of mathematics called discrete mathematics will be essential.
This book has a good selection of relevant topics: https://www.amazon.com/dp/1337694193

But most of the time you're probably not designing or analyzing algorithms. In ordinary work I'd say it's more about knowing to ask the right mathematical questions, whose answers will usually be simple arithmetic. "Can this variable overflow?" "How much memory will this take if we have X data points?" "How many iterations are we talking about here?" Things like that.

There's also one by the same name "Discrete Mathematics and it's Applications" but the author is K. Rosen. This would probably be better if you're self learning as there's a really comprehensive solutions manual that goes alongside it that can help you through the trickier bits.
 
Anyway, better people than I in this thread have said their piece about mathematics and programming before, so I'll shamelessly plagiarize their answers too:

Since it got brought up, I'll go into a little further depth with my answer and specifically how web developers in particular use math.

I mentioned the modulus in my previous answer. The modulus/modulo is an operator which tells you what the remainder is after dividing one number by another. For example, 7 mod 3 is 1, because 3 goes into 7 two times, and 3 times 2 is 6, and the difference between 7 and 6 is 1. As far as I know "remainders" is something you learn in elementary school algebra and then never again since they're kind of useless in most of the real world, but for web stuff they can be useful particularly for determining when to do something every Nth times. For example, it's often desirable to "zebra stripe" large tables so that subsequent rows (or columns) have different colors to make them easier to differentiate. The background color for even-numbered rows (in math terms, this means a number for which X mod 2 = 0; starting with zero, natch) will be white, but for odd-numbered rows, it will be light gray. That might look like this in pseudocode:

Code:
number_of_rows is 12;
current_row is 0;
while (current_row is less than number_of_rows) {
  if (current_row mod 2 equals 0) {
     background_color is white;
  else {
    background_color is light_gray;
  }
  draw_row(with color background_color);
  current_row is current_row + 1;
}

Some tables will have zebra-striping with three more columns, but the same type of math can apply; if (X mod 3) = 0, do the first color, else if (X mod 3) = 1, do the second color, else do the third color. Similar math comes into play if we're doing something like making a grid of images where each row of the grid will be X images wide.

Another thing that I probably should have mentioned in my previous answer is that web devs often use geometry when dealing with images, and particularly figuring out how to scale an image to a desired size, since it's wasteful to constantly be sending site visitors full-sized images. Let's say we have an image which is W pixels wide and H pixels tall. We need to scale it so that is no larger than 200 pixels wide. But if we just resize the width of the image without resizing its height correspondingly, then the aspect ratio of the image will be different from the image and it will look all distorted. So if we have an original image where W is 500 and H is 800, then when we set its width to 200, we need to set its height to (200 / 500) * 800 = 320 pixels in order for it to have the same aspect ratio. Similar math will come into play when we want to crop images.

All this is to say that while it will probably take non-programmers a while to remember how to do this sort of stuff from their high school math days, it's not trig and it's certainly not that difficult to master. So don't sweat about learning math if you want to get into programming. If you passed high school math without cheating too much, you can probably handle enough of the math parts to to make a decent living.

There are two aspects of my job which use stuff which I'd imagine is harder for people to grasp than the math parts. One is regular expressions. This is a way to basically tell a computer "in this lump of text, find bits of text which match this particular pattern." For example, you can use regular expressions to validate a phone number to ensure that a user entered a valid phone number into a field; it has the right number of digits and doesn't have anything unexpected like a letter. But at the same time, we want to be nice and allow the user some flexibility on how they enter it, so that they can enter it as "1 (555) 555-1234" or "555-555-1234" or "5555551234" and have all of those be valid, since that's just different ways of stating the same phone number (perhaps you've encountered site on the web which was pedantic about the formatting of such things when it didn't need to be). Regular expressions make this fairly easy to do, but since they're effectively an entirely separate programming language, and one which uses a whole bunch of symbols crashed together, they can be difficult to both write and read. A regular expression to validate a phone number like above might look like /1?[^\d]*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4})/ (don't at me).

The second is version control. Specifically Git since it's pretty much the industry monopoly at this point, but sometimes you end up working with a company still fixated on SVN or something (WHY ARE YOU USING FOSSIL, MISTER CLIENT. NOBODY USES FOSSIL EXCEPT YOU AND THE SQLITE PEOPLE AND I'M PRETTY SURE THEY ONLY USE IT FOR DOGFOODING PURPOSES.) First there's coming to grips with the idea of time traveling through the state of the filesystem, but then once you think you can wrap your head around that, Git throws all this funky vocabulary and syntax at you. Graphical tools help out a lot, but you're still going to need to learn the commands well enough to do stuff like deployment to servers.

I hope none of this is discouraging, though. Just to point out that for most reasonably intelligent people getting into most aspects of software development, there are scarier things you'll encounter than the math. Hope that helps… maybe it doesn't…
 
Last edited:
So the general consensus I'm getting is that math isn't a prerequisite to programming, but it does make shit generally easier to know it and you'll never get passed a certain point of quality without it, so hypothetically knowing as much as possible makes it as easy as possible.

A thing I've always had a problem with in math is that there's no linear path of mathematics grouped from necessity or difficulty, & there doesn't seem to be a encyclopedic compendium of it either, only a specific field or subject matter thereof. Does anyone have a source one could use to get, say, the "complete" material for mathematics?
 
  • Thunk-Provoking
Reactions: Strange Looking Dog
So the general consensus I'm getting is that math isn't a prerequisite to programming, but it does make shit generally easier to know it and you'll never get passed a certain point of quality without it, so hypothetically knowing as much as possible makes it as easy as possible.

A thing I've always had a problem with in math is that there's no linear path of mathematics grouped from necessity or difficulty, & there doesn't seem to be a encyclopedic compendium of it either, only a specific field or subject matter thereof. Does anyone have a source one could use to get, say, the "complete" material for mathematics?
This is a pretty good list (albeit ambitious as fuck, but on the upside many of the recommendations are freely available):
(https://archive.md/lcQvF)

As @Kosher Dill and @Ask Jeeves noted, Discrete mathematics is probably the most immediately applicable. Discrete mathematics is an umbrella term for the "just enough to be dangerous" selection of topics from set theory, logic, graph theory, number theory (in particular, the useful stuff like modulo arithmetic that @Least Concern elaborated on), probability, complexity theory, coding theory, and combinatorics. Each of those is a huge and fascinating subject in its own right, but most programmers (and heck, even most working mathematicians) will only ever use a relatively small subset of the stuff.

Other math is useful too, but perhaps only in more specialized situations. If you're interested though, you'd probably want to start with brushing up on the fundamentals (so yes: geometry and trig, i.e. all those sines and cosines and triangles and all of that nonsense) and some basic differential/integral calculus to use as a firm base.
 
So the general consensus I'm getting is that math isn't a prerequisite to programming, but it does make shit generally easier to know it and you'll never get passed a certain point of quality without it, so hypothetically knowing as much as possible makes it as easy as possible.

A thing I've always had a problem with in math is that there's no linear path of mathematics grouped from necessity or difficulty, & there doesn't seem to be a encyclopedic compendium of it either, only a specific field or subject matter thereof. Does anyone have a source one could use to get, say, the "complete" material for mathematics?
I might be talking out of my ass, but Concrete Mathematics by Donald Knuth was written as a foundational text for The Art of Computer Programming by the same author, and I've heard it's good.
 
Does anyone have a source one could use to get, say, the "complete" material for mathematics?
God made the integers, all else is the work of man. - L. Kronecker

Of all things, I think the Wikipedia list of "areas of mathematics" is actually quite good as a bird's-eye view:
https://en.wikipedia.org/wiki/Template:Areas_of_mathematics

Also try looking up "qualifying exams" for university math departments, if you want to see what's actually expected of a professional mathematician - mathematics is so big that no one will ever learn it all or master all its subfields. It varies per department, but algebra and analysis are universally required, and some sort of geometry/topology is another common requirement.

I might be talking out of my ass, but Concrete Mathematics by Donald Knuth was written as a foundational text for The Art of Computer Programming by the same author, and I've heard it's good.
Personally I don't find Knuth useful to learn from, either for algorithms or algorithm analysis. There are more accessible and practical choices in this day and age. I haven't used "Concrete Mathematics" myself, but it seems very much geared toward preparing you for TAOCP specifically.
 
Back