Programming Praxis – Sum

In today’s Programming Praxis exercise, our goal is to implement a unix checksum utility. Let’s get started, shall we?

Some imports:

import Data.Char
import System.Environment

I made two changes in the checksum algorithm compared to the Scheme version. I included to conversion to a string to remove some duplication and I used a simpler method of dividing and rounding up.

checksum :: String -> String
checksum = (\(s,b) -> show s ++ " " ++ show (div (b + 511) 512)) .
    foldl (\(s,b) c -> (mod (s + ord c) 65535, b + 1)) (0,0)

Depending on whether or not the program was called with any arguments, the checksum is calculated for either the stdin input or the files provided.

main :: IO ()
main = getArgs >>= \args -> case args of
    [] -> interact checksum
    fs -> mapM_ (\f -> putStrLn . (++ ' ':f) . checksum =<< readFile f) fs
About these ads

Tags: , , , , , , , ,

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: