Hacker News new | ask | show | jobs
by bluecalm 4264 days ago
Python doesn't have pattern matching but the code is basically the same. I guess better cases for showing off the feature are ones where the patterns aren't just True/False tuples.

    for i in range (1, 101):
    	fbsign = (i % 3 == 0, i % 5 == 0)
	if fbsign == (1, 1): print("Fizzbuzz")
	elif fbsign == (1, 0): print("Fizz")
	elif fbsign == (0, 1): print("Buzz")
	else: print(i)
3 comments

One difference is that this won't do exhaustiveness checks, where the pattern match will.
Well, here's an exhaustively checking version. Not statically still of course.

    for x in range(1,101):
        print [
                          # %3 = 0
        [      x,         "Fizz"  ],
        [   "Buzz",     "FizzBuzz"] # %5 = 0
        ][x%3 == 0][x%5 == 0]
(I'll note this was hard to get than if-checks and pattern matching so I won't be replacing such logic with matrices in my Python program any time soon...)
> not statically of course

Right, but that's the point!

Some people are sayint this is extremely non idiomatic python. I think most of the problem is not following the style guides. Here's a pep8 compliant solution that is a bit more idomatic, and almost as compact.

In Python, the way to do pattern matching is with dictionaries of functions.

    fizz_buzz = {(True, True): lambda x: "Fizzbuzz",
                 (True, False): lambda x: "Fizz",
                 (False, True): lambda x: "Buzz",
                 (False, False): lambda x: x}

    for i in range(1, 30):
        fbsign = (i % 3 == 0, i % 5 == 0)
        print(fizz_buzz[fbsign](i))
I see it as over thinking simple stuff. Maybe I think about performance too much but constructing a dictionary and then defining functions to do simple signature thing is imo just over designing things. Too much abstraction for expressing a simple concept. Performance aside, you need to go find the dictionary once you see code like that while with chain of if-else statements it's right there in front of your eyes.

As to 0 and 1 thing... Python has C'ish boolean (basically an integer type). Using True and False as numbers is completely standard as PEP 285 indicates. I tend to agree that maybe here using True/False is a bit more natural but it really is type-purity nitpick in my view.

Could you point out which part of PEP8 the code in my original post violates? While I don't really like a lot of currently popular style I see a lot of values in following the PEP's and long established conventions.

That's not genuinely pattern matching, however. It only works for patterns without member binding.
That is very non-idiomatic python. Use True and False instead of 1 and 0 when comparing the (boolean) result of a comparison.