by adamjc · 4y ago · 0 comments
> Functional programmers! Remember higher-order functions!
I didn't realise utilising HoF meant rolling your own interpreter ;).
Pure FP is very interesting, but having to write entirely without side-effects would be a real challenge for me. I use js+ramda[0], we effectively write our services as a `pipe`, you just stick in transforming fns whereever you need to, e.g.:
const handler = pipe(
fn1,
fn2,
fn3
)(event)
The underlying implementation of `fn1` for example doesn't need to be written in an fp paradigm, it can be written imperatively. You could then slowly-slowly chop out the imperative functions for fp ones if you really wanted, but IMHO some problems are best solved imperatively.My advice is instead: "Programmers! Remember to use the right tool for the job!"
Haskell isn't ill-suited for something like fizzbuzz at all, it's just _also_ suited for things like quickly writing interpreters and solving problems that way when it makes sense.
Why doesn't C#, Java, etc have the same problem with perception because they have the same "many ways" to solve problems.
"fun"
brainfuck is fun too and no one uses it.
Haskell is simple even if unfamiliar to you. Brainfuck is complex even if familiar to you.
FizzBuzz can be done more "normally" in Haskell with similar levels of simplicity as non-FP languages: https://wiki.haskell.org/Fizzbuzz
People who miss that are clearly looking hard for some reason to dismiss the work.
This seems very elegant and clean and I don’t know the slightest bit of Haskell other than “MONADS!!!”
My version looks like the below. I didn't originate the approach but I like this spelling. It won't make total sense to non-Haskellers though.
{-# LANGUAGE MonadComprehensions #-}
import Data.Maybe
import Data.Monoid
fizz :: Int -> String
fizz n = fromMaybe (show n) $ f 3 "Fizz" <> f 5 "Buzz"
where
f :: Int -> String -> Maybe String
f d msg = [msg | n`rem`d == 0]
main = mapM_ putStrLn [fizz n | n <- [1..100]]
This extends in an obvious way to FizzBuzzHissHowl, lets the Monoid instance manage concatenating the special tokens together while remembering if any of the rules have matched, and uses a monad comprehension on the Maybe monad to cleanly lift the token into the Maybe monad if the number is a multiple of whatever. The type annotation on f is added to make it a little bit clearer what is going on.The use of monoids and the monad comprehension may be slightly flashy, but the use of Maybe to remember whether a rule has triggered is second nature in Haskell.