News for hackers. Stuff that matters.
Re:Porting Graphing Calculator from C++ to Swift by gumby on Saturday July 02, 2022 @04:08PM (#31961909)
Curious what boilerplate is common in C++ that isn’t needed in Swift. I find the repetitive boilerplate level of C++ pretty minimal, especially compared to languages like Java.

Template specification used to need a lot of decoration but with auto most of that is gone.

Re:Porting Graphing Calculator from C++ to Swift by ChubbyGlasses on Sunday July 03, 2022 @03:43AM (#31965889)
I think there are different ways to look at boilerplate, some of which languages like C++ and Rust are great at handling through their standard libraries, but there is also code boilerplate that needs language support handle well. defer and C-style for loops being the most well known constructs where the language provides syntax for something that otherwise would be difficult to express with just functions and lifetimes. Swift goes a step beyond by providing syntax for many other common patterns (aka boilerplate).

For example, a few areas where Swift reduces boilerplate and the syntax it provides to do so:

  - a complete null/optional story: first class optional types (T? = Option<T>), null chaining (obj?.prop), and null coalescing (T ?? "default")

  - error handling: fn() throws Err (= fn() -> Result<T,Err>), try, try?, try!, do/catch (out-of-band error handling), w/o stack unwinding, see nulls

  - and struct/enum lifecycle management: constructors, getter/setter props, defaults, named functions, named tuples, etc. (this list is loong)

Individually each feature is small and could possibly be argued as bloat or overhead since you can accomplish the same with just regular functions and Rust-like code and abstractions, but combined they make the language feel more expressive (and more fun IMO) than would otherwise be possible and often without sacrificing performance. They also serve to reduce cognitive overhead in the same way using for loops is nicer than desugaring to while loops. This is nothing to say of the syntax itself, and a bunch of other small features; Swift really is a case where the whole is greater than the sum of of its parts.
Re:Porting Graphing Calculator from C++ to Swift by tomovo on Saturday July 02, 2022 @08:26PM (#31963833)
Headers? Awkward string manipulation? Very thin standard library? Fragmented build systems?

I would describe dealing with those issues as "boilerplate" because it's just a lot of code you should not have to write.

Swift is so much more comfortable and fun.

(btw I still love C++ and cross platform support completely flips the script)

Re:Porting Graphing Calculator from C++ to Swift by _gabe_ on Saturday July 02, 2022 @10:39PM (#31964571)
> Very thin standard library?

I'm not sure we're thinking of the same standard library if you would describe it as thin...[0]

[0]: https://docs.microsoft.com/en-us/cpp/standard-library/cpp-st...

Re:Porting Graphing Calculator from C++ to Swift by lifthrasiir on Saturday July 02, 2022 @10:51PM (#31964622)
That is still thin by the modern standard. More accurately speaking, C++ standard library has too many useless things and lacks too many useful things. Compare with D [1], Rust [2] or Zig [3].

[1] https://dlang.org/phobos/

[2] https://doc.rust-lang.org/std/

[3] https://ziglang.org/documentation/master/std/

Re:Porting Graphing Calculator from C++ to Swift by _gabe_ on Saturday July 02, 2022 @11:07PM (#31964696)
It looks like the only big feature any of these standard libraries contain that C++ doesn't are things like networking and json/xml parsers. I would argue that those should not be part of a standard library, but you can still easily get those through additional C/C++ libraries.

I honestly don't know what else you would be looking for in a standard library. C++ provides out of the box:

- hash maps

- sets

- dynamic arrays

- fixed length arrays

- bit sets

- option types

- atomics

- mutexes

- futures

- strings

- queues/stacks/Deques

- tuples

- variants

- streams

- etc

In addition, they have a huge range of algorithms that operate on all of these containers. I'm really curious, what does the standard library not have that you think forces you to write boilerplate?

Re:Porting Graphing Calculator from C++ to Swift by Const-me on Sunday July 03, 2022 @11:38AM (#31968503)
> what does the standard library not have that you think forces you to write boilerplate?

The streams from the standard library are broken beyond repair, I avoid them at all costs: https://www.moria.us/articles/iostream-is-hopelessly-broken/ Even <stdio.h> C header is much better abstraction, despite 50 years old.

To be useful, option types and tuples need language support. C++ doesn't have it.

Similarly, to be useful, futures need runtime support i.e. asynchronous I/O. They also need language support like async-await, to generate these state machines. C++ has none of them.

The standard library still does not really support Unicode, people need third-party libraries like ICU just to manipulate strings: https://stackoverflow.com/q/42946335/126995

Re:Porting Graphing Calculator from C++ to Swift by lifthrasiir on Sunday July 03, 2022 @12:15AM (#31965006)
I believe Rust has the most conservative standard library among those modern languages and it still has many things that the C++ standard library simply don't have (yet):

- Unified result types. C++23 is finally going to have `std::expected`, but it will probably take another version or two to see the `std::expected`-only version of standard library.

- Iterator utilities. Again, C++23 will see a significant improvement in <ranges> but that still falls short of what Rust `Iterator` provides by default.

- Checked arithmetic. Rust and many other languages distinguish checked and unchecked arithmetic and put one of them (typically unchecked one) into the standard library. C++ doesn't have anything like that.

- Guarded mutex (that is, a portion of memory by design only accessible when locked) and concurrent queue. C++ does support concurrency out of the box, but its tools are pretty bare bones and this is one example.

Re:Porting Graphing Calculator from C++ to Swift by _gabe_ on Sunday July 03, 2022 @08:26AM (#31967185)
Thanks for providing some specific examples! I still don't see how any of these would result in a 30% decrease in boilerplate. My main point was I feel like header files are the biggest piece of boilerplate and it seems weird to accuse the lack of features in the standard library as a reason for all the boilerplate.

Just a couple other points though, C++ provides fully customizable iterators. They don't have ranges, but ime the amount of times I need ranges vs just iterating over a container are relatively low. Also, is a lock guard in C++ not the same thing as a guarded mutex? This may be ignorance on my part because I'm not familiar with rust, but it sounds like the same thing to me. A lock guard will lock and automatically release a mutex once it goes out of the current scope.

Re:Porting Graphing Calculator from C++ to Swift by lifthrasiir on Sunday July 03, 2022 @11:23AM (#31968392)
You have a good point that featureful standard library doesn't necessarily result in less boilerplate, but I assumed that you kinda implied it by enumerating features. Frankly almost every feature you and I listed is not exactly relevant here---most of them can be easily refactored into external libraries ;-)

What I find most lacking from the C++ standard library is actually coherence. Different parts of standard library were developed separately from each other, and while adapters between them exists (e.g. stream iterators can be used with `std::format_to`) they are by definition boilerplates. Some parts are simply not relevant in the modern C++ programming and still have to be retained for compatibillity (e.g. `std::auto_ptr`). In this view C standard library is actually a lot more coherent than C++, even though C standard library itself is less powerful and featureful than C++.

> They don't have ranges, but ime the amount of times I need ranges vs just iterating over a container are relatively low.

I think this is simply because C++ iterators are less usable. All iterators can be technically rewritten as loops, so you may have internalized to avoid using iterators when iterators would be beneficial but difficult to use. I personally find myself using iterators a lot more in Rust than in C++.

> Also, is a lock guard in C++ not the same thing as a guarded mutex? This may be ignorance on my part because I'm not familiar with rust, but it sounds like the same thing to me. A lock guard will lock and automatically release a mutex once it goes out of the current scope.

I actually don't know the exact term (the name "guarded mutex/lock" was what I've used in the past), but I meant a mutex that is strongly coupled with some additional data so that the API prevents or at least discourages to access the data without acquiring the mutex. In a hypothetical design `std::mutexed<T>` will be `T` plus `std::mutex` and `std::lock_guard<std::mutexed<T>>` would have `operator *` which allows the access to `T`. In Rust [1] this is actually the default, and you never have a bare `std::mutex` (though it can be simulated with placeholder data, `Mutex<()>`).

[1] https://doc.rust-lang.org/std/sync/struct.Mutex.html

Re:Porting Graphing Calculator from C++ to Swift by _gabe_ on Sunday July 03, 2022 @03:10PM (#31970143)
> You have a good point that featureful standard library doesn't necessarily result in less boilerplate, but I assumed that you kinda implied it by enumerating features.

Gotcha, I appreciate the back and forth which helped me to clarify that point a bit better :)

> What I find most lacking from the C++ standard library is actually coherence.

I 100% agree. There are plenty of areas that C++ is very lacking, and I think this comment highlights that.

I initially started this thread off because a big complaint I hear among C++ users is the language is a bloated mess, which is why the parent comment saying that C++ had a thin standard library didn't ring true to me. But I think what you're saying here is closer to the truth. It has a lot of good features, but they're mostly after thoughts and poorly integrated. Whereas a language like Rust (or another modern language) has around the same amount of features builtin, but they're more focused, integrated, and planned :)

Re:Porting Graphing Calculator from C++ to Swift by socialdemocrat on Sunday July 03, 2022 @09:40AM (#31967628)
I think it makes sense to bundle with a standard module things which are quite OS independent and very commonly used like Python, Go, Swift, Julia and many other languages do: collections, common algorithms, File reading and writing, socket communication, async, concurrency, JSON and possibly simple XML. String manipulation, regular expressions.

What should clearly be outside is stuff like graphics library, GUI, HTML.

Re:Porting Graphing Calculator from C++ to Swift by _gabe_ on Sunday July 03, 2022 @03:02PM (#31970086)
> collections, common algorithms, File reading and writing, socket communication, async, concurrency, JSON and possibly simple XML. String manipulation, regular expressions

C++ does provide all of this in the standard library except for sockets, Json and XML. I think once you get to things like Json and XML it doesn't make much sense to include that in the standard library. There are plenty of applications that don't need or use either of those, and it's a shame to bundle some configuration language when somebody may have another preference like yaml or something. There's nothing wrong with providing additional standard add-ons that include these, but I definitely don't think it makes a lot of sense to bundle it in with the standard.

This is a whole separate conversation, but my main point was there are a lot of better things to pick on C++ for. Most complaints I hear are that it includes too many useless features haha.

Re:Porting Graphing Calculator from C++ to Swift by unnouinceput on Saturday July 02, 2022 @05:37PM (#31962694)
That makes 2 of us. When I've read "So much of the repetitive boilerplate code that was necessary for C++ melted away in Swift" my eyes rolled over. For me Swift repetitive boilerplate is on par with the one in C++. Clearly the author never touched Ada nor Python, if that's the number one reason he wanted another language to eliminate the repetitive boilerplate.

I suspect he just wanted to learn Swift and that's a good reason enough to make this rewrite, as he admits in the final paragraphs of the article: "I’ve enjoyed learning Swift and am much happier with the state of the code now"

Re:Porting Graphing Calculator from C++ to Swift by astrange on Saturday July 02, 2022 @10:53PM (#31964632)
C++ doesn't have a module system, so you either have to declare everything twice, or put all your code in header files, or both.
Re:Porting Graphing Calculator from C++ to Swift by interpol_p on Sunday July 03, 2022 @03:13AM (#31965751)
I don't write C++ much anymore, but to take an example where we want to union two sets (I'm sure the C++ one could be better? I've adapted from multiple examples)

C++:

    int first[] = {1,2,3,4};
    int second[] = {5,6,3,4};
    std::vector<int> v(8);
    std::vector<int>::iterator it;

    std::sort (first,first + 4);     // 1 2 3 4
    std::sort (second,second + 4);   // 3 4 5 6

    it = std::set_union (first, first + 4, second, second + 4, v.begin());

    v.resize(it - v.begin());

    for(it = v.begin(); it != v.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

Swift:

    let a = Set([1,2,3,4])
    let b = Set([5,6,3,4])
    let c = a.union(b)
    print(c) //prints "[1, 2, 3, 5, 6, 4]"
Re:Porting Graphing Calculator from C++ to Swift by nly on Sunday July 03, 2022 @05:28AM (#31966373)
In C++20 the full program, retaining the same algorithm, can look like this:

    #include <algorithm>
    #include <iterator>
    #include <vector>
    #include <iostream>

    using namespace std::ranges;

    int main()
    {
        std::vector a = {1,2,3,4};
        std::vector b = {5,6,3,4};
        sort(a);
        sort(b);
        decltype(a) c;
        set_union (a, b, back_inserter(c));
        copy(c, std::ostream_iterator<int>(std::cout, "\n"));
    }
https://gcc.godbolt.org/z/44Ksf1hK8

Note the value type deduction when declaring the vectors, the use of back_inserter to avoid having to resize the result (c) vector, the use of std::ranges to do away with all the begin + end crapola, and the way ranges and iterators are inter-mixed.

C++ is always going to be a bit more verbose in trivial cases, but it's not that bad, and exposes a lot more flexibility in complex ones.

Re:Porting Graphing Calculator from C++ to Swift by interpol_p on Sunday July 03, 2022 @10:54AM (#31968158)
Thanks for the modernised version! It looks a lot better
Re:Porting Graphing Calculator from C++ to Swift by gpderetta on Sunday July 03, 2022 @04:03AM (#31965979)

   std::set a{1,2,3};
   std::set b{5,6,3,4};
   std::set c{a};
   c.insert(b.begin, b.end());

   for(auto x: c)
      std::cout<<c<<' c;
   std::cout << '\n';
Re:Porting Graphing Calculator from C++ to Swift by heavyset_go on Saturday July 02, 2022 @05:44PM (#31962750)
Old code is going to have long implementations of things we take for granted now.
Re:Porting Graphing Calculator from C++ to Swift by jcelerier on Saturday July 02, 2022 @05:32PM (#31962651)
if the code started in the 80s, I doubt there's many autos or templates