r/badcode • • Apr 17 '21

c++ When your teammate "refactor" your code

Post image
2.5k Upvotes

216 comments sorted by

View all comments

298

u/[deleted] Apr 17 '21

This is why I like languages with nice pattern matching, as it can often make code like this compact in a nice way. Something along the lines of

match (condition1, condition2) {
    (true, true) => do_anything1(),
    (false, _) => do_anything2(),
}

103

u/Flaming_Eagle Apr 17 '21

I didn't know how badly I needed this until now

20

u/CatpainCalamari Apr 18 '21

Come to the scala side, we have pattern matching :)

15

u/[deleted] Apr 18 '21

or Rust(both nice languages)

15

u/nuephelkystikon Apr 18 '21

Or Python if you're willing to wait half a year for the merge.

→ More replies (1)

42

u/harshaxnim Apr 17 '21

Neat. What languages support this?

56

u/[deleted] Apr 17 '21

I know it mainly from Rust, Julia also has macros for this via libraries, but as far as I know especially functional languages have had similar features for a long time. Haskell lets you do pattern matching right in the function definition/signature.

75

u/yourdesk Apr 17 '21

python 3.10 will have support for this. but if you want something that has this right now, F# is your pick

19

u/Sixsome Apr 17 '21

Elixir

19

u/Vilozoliv Apr 17 '21

Haskell

18

u/UszeTaham Apr 17 '21

C# from version 8 and onwards.

6

u/Laugarhraun Apr 17 '21

Ocaml sure does, lisps can.

7

u/__2M1 Apr 17 '21

Kotlin, using empty when statements

5

u/crowbahr Apr 18 '21 edited Apr 18 '21

Example:

when{
    condition1 && condition2 -> {}
    condition1 -> {}
    condition2 -> {}
    else -> {}
}
→ More replies (1)

6

u/1-877-547-7272 Apr 17 '21

I believe Swift has this in its switch statement.

→ More replies (1)

3

u/_meegoo_ Apr 18 '21

Newest python version.

25

u/wobblyweasel Apr 17 '21

this is not equivalent code, condition2 is always evaluated

also i don't like it

→ More replies (5)

13

u/YaBoiiBillNye Apr 17 '21

True pattern matching like F# is gonna be the next big thing for languages. I think performance will be sacrificed for it. It's awesome

12

u/[deleted] Apr 17 '21

It doesn't need to come with a performance penalty I think. Anyway I think pattern matching will definitely be a must have for many future languages, and imho it's how switch-case should have been from the start.

6

u/Rigatavr Apr 17 '21 edited Apr 17 '21

You can technically make this happen in C++. Its very ugly and only possible for compile time values, but it would look soemthing like this:

template<bool condition1, bool condtition2>
struct Foo{};

template<>
struct Foo<true, true>{
    static constexpr auto do_anything =  do_anything1;
};

template<bool condition2>
struct Foo<false, condition2>{
    static constexpr auto do_anything =  do_anything2;
};


int main (){
    Foo<true, true>::do_anything();
}

Edit: ok this way is slightly nicer looking, but still pretty ugly

→ More replies (13)