Hacker News new | past | comments | ask | show | jobs | submit login

Here's the same approach in F# without the different types of String; therefore, easier to get more functional.

    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)



And racket, just for kicks

    #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)))


Haskell -

  fizzbuzz x = case (x `mod` 3, x `mod` 5) of
      (0, 0) -> "FizzBuzz"
      (0, _) -> "Fizz"
      (_, 0) -> "Buzz"
       _     -> show i

  mapM_ (putStrLn . fizzbuzz) [1..100]


Pattern matching is one of the ways to get "two-mod" code where the modulus operator is used two times. For example, string concatenation and assignment operators do the same in this Python code:

    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.


Currying often allows for elegant point free code. Like in your last line, for F# they could also have written

    [1..100] |> List.iter (fizzbuzz >> printfn "%s")


Nice F# snippet! This just looks so simple and elegant. As another approach, the "enum" types the OP mentions map to discriminated unions in F#.

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")


Although I love pattern matching, I find the solution with 'if' more legible and no less functional.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: