|
|
|
|
|
by Tarean
3427 days ago
|
|
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. |
|