Re:Why your first Rust FizzBuzz implementation may not work
by bluecalm on Monday October 13, 2014 @04:02AM
(#8447878)
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.
[ Parent
| on HN ]
Re:Why your first Rust FizzBuzz implementation may not work
by steveklabnik on Monday October 13, 2014 @04:10AM
(#8447894)
One difference is that this won't do exhaustiveness checks, where the pattern match will.
Re:Why your first Rust FizzBuzz implementation may not work
by Erwin on Monday October 13, 2014 @05:03AM
(#8447995)
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...)
Re:Why your first Rust FizzBuzz implementation may not work
by steveklabnik on Monday October 13, 2014 @07:05AM
(#8448218)
> not statically of course
Right, but that's the point!
Re:Why your first Rust FizzBuzz implementation may not work
by Wilduck on Monday October 13, 2014 @10:23AM
(#8448810)
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))
Re:Why your first Rust FizzBuzz implementation may not work
by bluecalm on Monday October 13, 2014 @08:42PM
(#8451374)
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.