Posts Tagged ‘knuth’

Programming Praxis – Trabb Pardo Knuth Algorithm

April 27, 2012

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