In today’s Programming Praxis exercise, our goal is to implement a simple algorithm that could serve as an alternative to FizzBuzz. Let’s get started, shall we?
A quick import:
import Control.Monad
The algorithm calls for applying a function to values. We could ofcourse inline it since in Haskell that’s technically still a case of applying a function, but I think making it a separate function better matches the spirit of the description.
f :: Double -> Double f x = sqrt (abs x) + 5 * x^3
The algorithm itself is fairly trivial: read the numbers, reverse them, apply the function and print the result or an overflow message.
main :: IO () main = mapM_ (putStrLn . (\x -> if x > 400 then "TOO LARGE" else show x) . f) . reverse =<< replicateM 11 readLn
Tags: bonsai, code, fizzbuzz, Haskell, kata, knuth, pardo, praxis, programming, The Early Development of Programming Languages, trabb
May 4, 2012 at 6:23 pm |
I tried this alternative definition of main and got the same result:
main = interact $ unlines . (map ((\x -> if x > 400 then “TOO LARGE” else show x) . f . read)) . reverse . lines
I generally prefer, when possible, to think about lists of lines rather than to think explicitly about Monads. In your code, did you use mapM_ out of preference or for performance reasons?
May 4, 2012 at 7:24 pm |
Just convenience really. I doubt there’s that much of a performance difference, and with only 11 lines it wouldn’t matter of there was. The main reason I don’t use interact that often is that (at least on Windows) you have to manually end the input with ctrl+z, whereas the monadic version automatically stops after 11 lines.