fizzbuzz = fn(x) ->
case {rem(x, 3) == 0, rem(x, 5) == 0} do
{true, false} -> IO.puts "fizz"
{false, true} -> IO.puts "buzz"
{true, true} -> IO.puts "fizzbuzz"
_ -> IO.puts x
end
end
Enum.each Range.new(1, num), fizzbuzz
Since functions are also pattern matched in Elixir (and Erlang!) it could also be done without using case and handled purely as functions. defmodule FizzBuzz do
def fizzbuzz(x), do: fizzbuzz(x, {rem(x, 3), rem(x, 5)})
def fizzbuzz(_x, {0, 0}), do: IO.puts "fizzbuzz"
def fizzbuzz(_x, {0, _}), do: IO.puts "fizz"
def fizzbuzz(_x, {_, 0}), do: IO.puts "buzz"
def fizzbuzz(x, {_, _}), do: IO.puts x
end
Enum.each Range.new(1, 100), &FizzBuzz.fizzbuzz/1
or in a more ruby-esque fashion (1..100) |> Enum.each fn(x) ->
cond do
rem(x, 3) == 0 and rem(x, 5) == 0 ->
IO.puts "fizzbuzz"
rem(x,5) == 0 ->
IO.puts "buzz"
rem(x,3) == 0 ->
IO.puts "fizz"
true ->
IO.puts x
end
end 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) 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...)Right, but that's the point!
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))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.
Will Rust's type checker warn you of a non-exhaustive pattern match?
The new bespoke scheme gives approximately the same results as HM but is drastically simpler. For all I know this could inhibit Rust's future ability to do even more powerful things with types, but AIUI this scheme has the advantage of being actually decidable given the extensions to HM that we would require in the current language.
I ain't a type theorist though, so take this as hearsay. :)
I'm curious (and a bit skeptical) of your claim that the scheme is "drastically simpler" than HM. HM is a beautifully simple design, which can be expressed (abstractly) in just a couple of lines.
http://smallcultfollowing.com/babysteps/blog/2014/07/09/an-e...
"This scheme simplifies the code of the type inferencer dramatically and (I think) helps to meet our intutions (as I will explain). It is however somewhat less flexible than the existing inference scheme, though all of rustc and all the libraries compile without any changes."
let fizzbuzz num =
match num % 3, num % 5 with
| 0,0 -> "FizzBuzz"
| 0,_ -> "Fizz"
| _,0 -> "Buzz"
| _,_ -> num.ToString()
[1..100]
|> List.map fizzbuzz
|> List.iter (fun (s:string) -> printfn "%s" s) #lang racket
(define (fizz-buzz n)
(match (list (modulo n 3) (modulo n 5))
[(list 0 0) "FizzBuzz"]
[(list 0 _) "Fizz"]
[(list _ 0) "Buzz"]
[_ n]))
(for [(i (range 100))]
(displayln (fizz-buzz i))) fizzbuzz x = case (x `mod` 3, x `mod` 5) of
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
(_, 0) -> "Buzz"
_ -> show i
mapM_ (putStrLn . fizzbuzz) [1..100] for i in range(1, 101):
x = ""
if i % 3 == 0:
x += "Fizz"
if i % 5 == 0:
x += "Buzz"
if x == "":
x += str(i)
print(x)
If anybody is randomly curious it can be fun to solve FizzBuzz in Haskell the same way that this Python code does it, but (to be more idiomatically Haskell) storing the FizzBuzz success in a Maybe (or some other variable). If you define the appropriate `~>`, and higher-precedence `|~`, and higher-precedence `|~~>`, you can write the above function as: fizzbuzz x =
mod x 3 == 0 ~> "Fizz"
|~ mod x 5 == 0 ~> "Buzz"
|~~> show x
It's interesting because it's sort of a "follow-through guards" situation; the (|~) operator can at least be turned into a type signature of (Monoid m) => Maybe m -> Maybe m -> Maybe m. [1..100] |> List.iter (fizzbuzz >> printfn "%s")FWIW your final wildcard match can be (modestly) simplified to just
| _ -> num.ToString()
and the last line can be distilled to just |> List.iter (printfn "%s")It refuses to compile entirely.
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.
def fizzbuzz x
case [x % 3 == 0, x % 5 == 0]
when [true, false] then puts "fizz"
when [false, true] then puts "buzz"
when [true, true] then puts "fizzbuzz"
else puts x
end
end
The one and only time I was asked FizzBuzz in an interview, I wrote it this way, so it's not all that contrived (in my opinion, anyway!)For example in OCaml the match statement would be:
match ( i mod 3, i mod 5) with
| (0,0) -> Printf.printf "Fizzbuzz"
| (0,_) -> Printf.printf "Fizz"
| (_,0) -> Printf.printf "buzz"
| (_,_) -> Printf.printf "%d" i
Other than the irrelevant syntax bits like 'with', the semantics are identical, in order matching with no fall through, and _ for unnamed and unused bindings.To me with very limited experience in it, Rust really feels like OCaml with a skin that C programmers will understand.
:D
If you have the time, as you do this, I'd love to hear about your experience. Email me any time.
(I maintain Rust's docs, and am also starting to write some introductory curriculum. Hearing from people like you is _invaluable_.)
However, I would have expected rustc to complain about unused variables in
fn main() {
for i in range(1i, 101) {
match (i % 3, i % 5) {
(0, 0) => println!("Fizzbuzz"),
(0, a) => println!("Fizz"),
(b, 0) => println!("Buzz"),
c => println!("{}", i),
}
}
}
but neither the playpen nor yesterdays snapshot complains. And if you want to suppress warnings about unused variables, you prefix the variable with an underscore, or just use only the underscore, which got common to mean "I don't care what value gets bound to this name.". fn main() { let a = 0u; }
compiles with warning: unused variable: `a`, but fn main() { let _a = 0u; }
compiles silently.If you were to start a hypothetical project written in Rust, what would it be? I'm looking for something to cut my teeth on.
It's still easier when you've solved the problem previously, however.
A result of applying this approach to languages in general would be only knowing a couple of fairly similar languages. Which is bad. Really, really bad. Language influences our way of thinking in a non-trivial way, knowing only one kind of language is limiting.
Even worse, you're going to forever stay constrained to one family of languages that you didn't (probably) even chose yourself. In a current world it's ok if you were introduced to a C-like language as your first, but what if it was Pascal or Scheme?
In short: DON'T DO THIS. Learn more languages, the more FOREIGN (ie. you can't understand anything without docs) the BETTER. The 'intuitive' languages only let you express the same solution again and again, while breaking AWAY from your intuitions and learning 'non-intuitive' languages let's you see and implement DIFFERENT solutions.
(0, *) seems more obvious in that example than (0, _) but at least we are used to ____ in the forms printed on paper too.
As an experiment of what? Whether rust code makes somewhat sense to you depends to an extent on what languages you already know (I guess ML languages would help). Same as with Ruby and Python.
function fizzBuzz(i) {
switch(i % 15) {
case 0: return "fizbuzz";
case 5:
case 10: return "buzz";
case 3:
case 6:
case 9:
case 12: return "fizz";
default: return i.toString();
}
}
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].map(fizzBuzz) match i % 15 {
0 => FizzBuzz,
5 | 10 => Buzz,
3 | 6 | 9 | 12 => Fizz,
_ => Number(i),
}And to be clear, I like pattern matching. A lot. I just don't feel this really shows it off that well.
Your code is considered bad practice in many languages.