In today’s Programming Praxis, our goal is to print the numbers 1 through 1000 without using loops or conditionals. Let’s get started, shall we?
import Control.Exception import Control.Monad.State
The problem with this question is that it isn’t very well-defined. For example, the idiomatic way of doing this in Haskell would be the following:
loopy1 :: IO () loopy1 = mapM_ print [1..1000]
This has no loops or conditionals in the user’s code. However, the .. construct probably uses a loop and/or conditional internally. So let’s get rid of it:
loopy2 :: IO () loopy2 = f 1 where f 1000 = print 1000 f n = print n >> f (n + 1)
This uses recursion instead of looping and pattern matching instead of conditionals. However, you might consider pattern matching a number to be sufficiently like conditionals to be cheating. Ok, let’s choose another approach.
loopy3 :: IO () loopy3 = handle (\DivideByZero -> return ()) $ f 1 where f n = seq (div n (1001 - n)) print n >> f (n + 1)
Here we still use recursion, but we now end through exception handling rather than pattern matching. The only thing left to do would be to get rid of recursion, since you could consider that a form of looping.
loopy4 :: IO () loopy4 = evalStateT (do10 . do10 . do10 $ next) 1 where next = (liftIO . print =<< get) >> modify succ do10 f = f >> f >> f >> f >> f >> f >> f >> f >> f >> f
And there we go. No conditionals or looping of any kind as far as I can tell. This is probably the closest to the spirit of the exercise.