Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Likewise, using "match", I think the Clojure solution for FizzBuzz is very elegant:

    (doseq [n (range 1 101)]
      (println
        (match [(mod n 3) (mod n 5)]
          [0 0] "FizzBuzz"
          [0 _] "Fizz"
          [_ 0] "Buzz"
          :else n)))
To my mind, this reads much more clearly than if I wrote a bunch of if() statements.


What makes it clearer? I think you're just more used to "match", whereas other people are more used to "if".

The structure is almost identical. You even have an "else" clause!


:else is a convention in Clojure that has truthy keywords. You could replace that with anything that evaluates to true, like :foo, or true, or 1, etc.


But don't you see what I'm saying? I assume the order is important, and if the else: (or whatever else you decide to use) were first it would match everything and prevent the other cases from being used. So it's exactly equivalent to an if/elif/else chain. The structure is the same.


Things can be semantically equivalent but more elegant, easier to read, and harder to make mistakes.

I think most function programmers are actually very familiar with the patters found in Java. It's often one of the reasons they fell in love with more functional styles of programming.


Nice because it is readable but I generally dislike clever/elegant solutions for fizzbuzz. Here is my own clever haskell solution:

  module Raindrops (convert) where
  import Control.Monad (liftM2)
  import Data.Foldable(fold)
  import Data.Maybe (fromMaybe)

  convert = build rules
  build = liftM2 fromMaybe show . fold
  rules = uncurry rule <$> [(3, "Pling"), (5, "Plang"), (7, "Plong")]
    where rule i s j = if j `mod` i == 0 then Just s else Nothing

Short explanation: the fold function combines lists of monoids. In this case it combines three seperate monoids and does `[Int -> Maybe String] -> Int -> Maybe String`. It takes a list of functions that might create a string from a number, gives them all the same input and concats all strings that were returned. If none were returned the result stays Nothing and is then replaced by the string representation of the input via fromMaybe.

I like this solution because it shows how powerful it is to abstract over these concepts but also that trying to be too clever quickly ends in impossible to follow complexities.




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

Search: