Programming Praxis – Trabb Pardo Knuth Algorithm

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: , , , , , , , , , ,

2 Responses to “Programming Praxis – Trabb Pardo Knuth Algorithm”

  1. gcbenison Says:

    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?

  2. Remco Niemeijer Says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: