In today’s Programming Praxis exercise, our goal is to implement the fortune Unix command line tool. Let’s get started, shall we?
Some imports:
import Control.Monad import System.Environment import System.Random
Since we wrote some code in a previous exercise to select a random item from a list we can just use that here again:
chance :: Int -> Int -> a -> a -> IO a chance x y a b = fmap (\r -> if r < x then a else b) $ randomRIO (0, y-1) fortune :: [a] -> IO a fortune = foldM (\a (n,x) -> chance 1 n x a) undefined . zip [1..]
All that’s left to do to implement the fortune program is to read the appropriate file and choose a random line.
main :: IO () main = putStrLn =<< fortune . lines =<< readFile . head . (++ ["fortunes.txt"]) =<< getArgs
Four lines versus the 23 of the C version. Not bad.
Tags: bonsai, code, command, fortune, Haskell, kata, line, praxis, programming, random, unix