16 ms·
Why your first Rust FizzBuzz implementation may not work
- shurcooL 12y agoThat was informative... and it reinforced my perception of Rust as something to look into if I ever have to do something that absolutely necessitates the use of something low level like C++/Assembly. But for everything else that I can get away with (and that is a lot so far) I'll stick with Go because it's so much faster and shorter to write.
- dbaupp 12y ago> it's so much faster and shorter to write This is not obviously true to me, Rust provides more tools for building abstractions, even just "handle errors less manually"-abstractions, so they're possibly not that different (this certainly applies to the 'shorter' section). I guess it may be true for the things Go is suited/designed for; time and experience will tell.
- burntsushi 12y agoAnecdotes and personal opinions follow. I'm pretty happy with the speed at which I write Rust code, but I can definitely churn out Go code more quickly. (Probably on the order of how quickly I can write Python, although refactoring Go code is much faster.) I'm not sure exactly why, but my guess is that there are fewer abstractions to deal with (and fewer opportunities to make abstractions). I have written several medium Go applications (near or above 10 KLOC, which ideally, I would never hit in a dynamic language), and I'm pretty happy with how the code turned out in all but one of them. (But that one is a window manager.) I haven't yet written a similarly sized Rust application, though. I do write Rust code more quickly that I write Haskell code though. :-)
- dbaupp 12y agoYeah, that's why I focused on 'shorter' more than 'quicker'. (And I wasn't saying it is not true, just pointing out that it's cut and dried.)
- dbaupp 12y agoWhoops! I mean: that it's not cut and dried.
- Daishiman 12y agoBear in mind that Rust's APIs still have a lot of work remaining in their ergonomics, and this is likely what slows down the daily grind the most.
- wycats 12y agoI think it's, in general, useful to differentiate the speed of code-writing as a new developer and the speed of code-writing as an experienced developer. The reality is that people have very little time to try out new languages, and have to rely on anecdotes about the long-term cognitive costs of things like this. My personal experience is that many of the seemingly more-onerous things about Rust end up falling away once the rhythm of programming sets in. This is likely similar to how the error-handling approach of Go looks onerous at first, but seems to be something that doesn't slow people down too much in practice.
- retroencabulato 12y agoIf something absolutely necessitates using C++, why not use C++? (I'm genuinely asking.)
- mkesper 12y agoBecause BUGS. http://doc.rust-lang.org/nightly/intro.html#safety-%3Cem%3Eand%3C/em%3E-speed http://doc.rust-lang.org/nightly/intro.html#safety-%3Cem%3Ea...
- shurcooL 12y agoBecause writing and compiling code/projects in it is very painful. Header files, custom makefiles, etc.
- frankzinger 12y agoPardon me, but 'custom makefiles' have absolutely nothing to do with C++. There are IDEs with C++ support. Also, while working with headerless languages may be easier, calling working with headers 'very painful' is hyperbole.
- Tyr42 12y agoIrregardless of IDEs, I'd still need to learn how to use cmake and other systems to build and use libraries. It's a large pain compared to `pip install ...`.
- frankzinger 12y ago...need to learn how to use cmake and other systems to build and use libraries. On OSes for which this is true you'd be forced to compile python yourself as well, because it's also just a dependency (of pip, for one!) written in a compiled language. Edit: My point is: usually it's as easy as 'yum install', but on the rare occasion you will need to compile, I admit. However, that could happen with pip too; don't tell me its repos are always completely up to date. And in those cases it won't be quite as simple as 'pip install'.
- Hello71 12y agofor i in range(1, 101): print('FizzBuzz' if i % 15 == 0 else 'Buzz' if i % 5 == 0 else 'Fizz' if i % 3 == 0 else i) python doesn't have expressions? oh dear me.
- burntsushi 12y agoThe OP's characterization is reasonably accurate in my experience. I've run into several Python programmers who didn't actually know about Python's special "if expression" syntax. Moreover, the code you've presented here certainly isn't idiomatic, which counts for something.
- Hello71 12y agosure, but when you're implicitly comparing code segments (by placing them next to each other), you should at least make the effort to make them more the same, instead of pointing out that one language is missing a feature used in the other language, especially when this claim is false. the formatting can of course be improved: for i in range(1, 101): print('FizzBuzz' if i % 15 == 0 else 'Buzz' if i % 5 == 0 else 'Fizz' if i % 3 == 0 else i) there's also a suspicious "return" at the end of the second code segment which mysteriously appeared some time after the first one; looks like the author was trying a little too hard to differentiate python and rust.
- burntsushi 12y agoI disagree. I think code comparisons should be done using idiomatic code. I personally would not consider chaining `if` expressions like you've done here idiomatic Python.
- Hello71 12y agoand yet people write: let result = if i % 15 == 0 { "FizzBuzz" } else if i % 5 == 0 { "Buzz" } else if i % 3 == 0 { "Fizz" } else { i }; in rust? either this is good, readable code or this is poorly written, unintelligible code. you cannot make the argument that sometimes it is readable and sometimes not based on the presence of braces.
- aftbit 12y agoWhat's up with the "alternative" form of Python? What about braces, semicolons, and an explicit main() function makes that version worth showing?
- TillE 12y agoWell, "from __future__ import braces" is a joke, so applying the transitive property of jokes, I assume this alternative version is a joke as well.
- chrismorgan 12y agoIndeed it is. And people should certainly try executing `from __future__ import braces` if they’re not familiar with what it is. As for the main function and `if __name__ == '__main__': main()`, that part is actually generally recommended.
- GhotiFish 12y agoThe feature list in rust really does have my eye. The biggest one in particular was type inference. The reason type inference was such a big one was because if you use it right, annoying situations like "Two types of strings? What is this?" go the hell away. You have three types, static built in and binary strings, and a third that only makes the gaurentee that the datatype can do all the things a string aught to be able to do, and from there the compiler works out the practical implementations. This article has done a great job in killing my enthusiasm for the language. I guess it's implementation of type inference only goes as far as golangs, in that const keyword. Maybe I was being a bit naive in what I was expecting, hell maybe what I'm expecting isn't reasonably possible. bleh.
- dbaupp 12y agoRust has type inference similar to Haskell: type information can flow "backwards". It is very different to Go and C++ where types of locals are 'inferred' from their initialiser, and nothing else. E.g. fn main() { let mut v; if true { v = vec![]; v.push("foo"); } } is a valid Rust program: the compiler can infer that `v` must have type `Vec<&str>` based on how it is used. I don't think it's possible to syntactically write a Go program at all similar to this (a variable has to be either initialised or have a type), and the C++ equivalent (using `auto v;`) is rejected, as `auto` variables need an initialiser.
- pbsd 12y agoThe C++ analogous, although not exactly the same, is to use a `make_vector` wrapper, like template<typename...Args> inline auto make_vector(Args&&...args) { using T = typename std::common_type<Args...>::type; return std::vector<T>{{std::forward<Args>(args)...}}; } ... auto v = make_vector("asd", "dsa", std::string("asdsa")); It will obviously not deduce types after the vector is declared, but it's as close as one gets to type deduction based on the vector's content. There is one instance in C++ where information does flow backwards in a sense: disambiguating template overloads. For example, using fn_type = std::vector<int>(&)(int&&,int&&,int&&); auto v = static_cast<fn_type>(make_vector)(1, 2, 3); In this case, the static_cast information flows "back" to the type deduction of `make_vector` to deduce what Args&& is. This is not very useful, just a curiosity.
- yaccz 12y agomeh. fizz x = mod x 3 == 0 buzz x = mod x 5 == 0 fizzbuzz x | fizz x && buzz x = FizzBuzz | fizz x = Fizz | buzz x = Buzz | otherwise = NoFizzBuzz x data FizzBuzz = Fizz | Buzz | FizzBuzz | NoFizzBuzz Int instance Show FizzBuzz where show Fizz = "Fizz" show Buzz = "Buzz" show FizzBuzz = "FizzBuzz" show (NoFizzBuzz x) = show x main = mapM_ (putStrLn . show) $ map fizzbuzz [1..101]
- icedog 12y agoPutting the String issue aside, I just wanted to show the beauty of pattern matching. for i in range(1i, 101) { match (i % 3, i % 5) { (0, 0) => println!("Fizzbuzz"), (0, _) => println!("Fizz"), (_, 0) => println!("Buzz"), _ => println!("{}", i), } } -- edited: removed `.to_string()`, thanks chrismorgan
- chrismorgan 12y agoI contemplated using `match` in the article, but decided that there was enough to think about and that it was long enough already. Thanks for pointing it out, though—it certainly is a great thing!
- sillysaurus3 12y agoI guess beauty is in the eye of the programmer. I'd choose Python's or Ruby's FizzBuzz. It's beautiful that everyone can immediately understand those. This one, not so much. As a little experiment, I've deliberately avoided learning Rust to see if I can understand its idioms without reading any docs. I can sort of guess at what's going on here by reverse engineering what should happen with FizzBuzz, but it's not at all intuitive. For example, as an outsider, I'd expect it to be (0, 1) instead of (0, 0) since it's matching both the 0th and 1st patterns. Whereas (0, _) would be "0th pattern but not the 1st," or something, even though that really wouldn't make much sense because "0" would refer to which pattern it's matching, rather than the position of the argument determining which pattern it's matching. Etc. If Rust is the most robust way to solve a problem, it should naturally catch on. It seems pretty promising in that regard. EDIT: As a counter to my comment, my argument would be equally applicable to Lisp, and Lisp is beautiful. So my argument is probably mistaken. Maybe someone has to learn a language before judging whether it's beautiful.
- chrismorgan 12y agoIt’s whether (i % 3, i % 5) is equal to (0, 0) et al., where _ means “any value”.
- 12y ago
- wycats 12y agoFor what it's worth, String in Rust is similar to StringBuffer in other languages. You can append to a String; you can't append to a slice, which always represents a fixed view. A slice has storage that is borrowed from somewhere else, but it itself does not have its own storage. When you type `"foo"`, you are creating "static" storage (in the binary) and the slice is borrowed from that fixed-position location in memory. Mostly, your functions produce Strings and consume slices.
- chrismorgan 12y agoAnd that indeed is the real distinction between what Rust has and what other languages tend to have—the fact that &str doesn’t have its own storage. The equivalent to string types in other languages would be more like SendStr. That functions produce Strings and consume slices is a good way of expressing it.
- hrjet 12y agoBut shouldn't they (String and slice) have some common super type to make this all easy to use?
- wycats 12y agoYes. It's a design bug that String and slice don't share a common trait and that `.as_slice()` is common simply to use slice methods. I expect that to be fixed before 1.0.
- dhon_ 12y agoIn the contrived Python example, FizzBuzzItem is only called if the result is a number (not in any of the modulo 0 cases) - is that intended? I can see that it works, but it's breaking the analogy for me with the Rust code.
- chrismorgan 12y agoWhoa, that was indeed a mistake. Sorry about that. Fixed.
- dhon_ 12y agoThanks, also is the "try it" link on rust playpen linking to the wrong code?
- chrismorgan 12y agoNo, that’s the code that is supposed to be there. It’s indicating that there is nothing that you can put as the lifetime there.
- Padding 12y ago> There is a trade‐off here for them; as a general rule, such languages have immutable strings This is a bit disingenuous. I understand what he's aiming at, and he also mentions StringBuilder later on, but saying that a GC necessatites immutable strings is simply not true. As a counterexample: PHP has mutable strings and uses copy-on-write in situations where it "feels" that conflicts could occur. (Granted PHPs rules on how it handles its variables is a bit arbitrary and magical, and PHP didn't have a GC till version 5.3 .. but the argument still stands.)
- chrismorgan 12y agoYes, I know I was being rather fuzzy there. I was intending to give a general impression of where the differences lie.
- mihai_ionic 12y agoHere's what the final example from the blog would look like, if you were to directly translate it into C++: http://coliru.stacked-crooked.com/a/265c6ec6fb6751a9 http://coliru.stacked-crooked.com/a/265c6ec6fb6751a9 Now, of course, no one would program that way, but I think it does help visualize what really happens. The obvious cost from delaying the printing is that you have to branch a second time, later in the code, to consume the value. I wonder how feasible it would be to introduce some kind of compiler transform that could invert the control flow, essentially pasting the surrounding code into the inner branches, to make this abstraction cost-free.
- michel-slm 12y agoWhile FizzBuzz is a low-pass filter in most languages, with Rust it makes for a fascinating window into the language design!
- JBiserkov 12y ago... and therefore a viable interview question :)
- lmm 12y agoScala guy here. This kind of thing is useful - I'm happy to pay the costs of garbage collection so I don't need it for ownership, but for separating out async operations from sync operations, or database-transactional operations from non-database operations, it's great to be able to represent that difference in the type system (and without a huge syntactic overhead). But then if you want to abstract over types like MaybeOwned, you need higher-kinded types to be able to work with them effectively. Has Rust got any further towards implementing those?
- mhaymo 12y agoUnfortunately I don't think higher-kinded types are planned for Rust 1.0. See the rfc: https://github.com/rust-lang/rfcs/issues/324 https://github.com/rust-lang/rfcs/issues/324 and this HN thread: https://news.ycombinator.com/item?id=7997926 https://news.ycombinator.com/item?id=7997926
- Argorak 12y agoThey plan an aggressive release schedule, though: http://blog.rust-lang.org/2014/09/15/Rust-1.0.html#release-process http://blog.rust-lang.org/2014/09/15/Rust-1.0.html#release-p... So they could come in one of the post 1.0 releases and that could possibly be soon.
- Robadob 12y agoI've always liked this c++ implementation of FizzBuzz, its not the most clear or logical but its short; const char* outs[] = { "%d\n", "Fizz\n", "Buzz\n", "FizzBuzz\n" }; for (int i = 1; i < 101; i++) printf(outs[((((i%5)==0)<<1)+((i%3)==0))], i);
- heinrich5991 12y agoIs that allowed by the standard? (Passing a parameter to `printf` but not referencing it, in the non-"%d\n" case?)
- kps 12y agoC11 §7.21.6.1 If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. but that's just a consequence of stdarg, which does not require all supplied arguments to be consumed.
- jerf 12y agoYou know Rust team, it almost might be worth specializing this exact error message about mismatched string lifetimes to include a URL to this post, if not mismatched lifetimes in general. You know it's going to be a FAQ....
- steveklabnik 12y agoWe have unique diagnostic codes for each error, and I have plans (and an in-progress PR) that points to a web page with a much longer "this is what this error looks like, here are some strategies with how to fix it" in the works.
- donatj 12y agoThe meandering run-on garden path sentences make this post very hard to follow at times.
- chrismorgan 12y agoYeah, I’m afraid I do have a bit of a tendency to letting that happen.
- blt 12y ago"may not compile" would be a better title than "may not work". To a programmer familiar with compiled languages, "may not work" implies that the code will compile but produce the wrong result/a crash/undefined behavior. Rust aims to catch mistakes at compile time, so the headline is quite sensational under this interpretation.