Personal tools

Simple Unix tools

From HaskellWiki

Revision as of 06:40, 22 September 2006 by DonStewart (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Simple unix tools written in Haskell.

This is intended as a beginners tutorial for learning Haskell from a "Lets just solve things already!" point of view.

--
-- Some unix-like tools written in elegant Haskell
--
 
import Data.List
import Data.Char
import System.IO
import Text.Printf
 
-- 
-- First, a useful helper
--
input f = interact (unlines . f . lines)
 
--
-- The 'cat' program
--
cat   = input id
 
--
-- Sort a file
--
sort' = input sort
 
-- 
-- Reverse a file (tac)
--
tac   = input reverse
 
--
-- Return the head -10 line of a file
--
head' = input $ take 10
 
--
-- Remove the first 10 lines of a file
--
drop' = input $ drop 10
 
--
-- Return the tail -1 line of a file
--
tail' = input $ (:[]) . last
 
--
-- remove duplicate lines from a file (like uniq)
--
uniq  = input nub
 
--
-- double space a file
--
space = input $ intersperse []
 
-- 
-- repeat the input file infintely 
--
iterate = interact cycle
 
--
-- remove the first occurence of the line "str"
--
remove  = input $ delete "str"
 
--
-- make a file all upper case
--
upper   = interact $ map toUpper
 
--
-- remove leading space from each line
--
clean   = input $ map (dropWhile isSpace)
 
--
-- join lines of a file
--
join    = input $ (:[]) . concat
 
--
-- Translate the letter 'e' to '*', like tr 'e' '*' (or y// in sed)
--
y     = interact $ map f
    where f 'e' = '*'
          f  c  = c
--
-- Filter the letter 'e' from a file, like tr -d 'e'
--
tr    = interact $ filter (/= 'e')
 
--
-- Count number of characters in a file (like wc -c)
--
wc_c  = interact $ show . length
 
--
-- Count number of lines in a file, like wc -l
--
wc_l  = interact $ show . length . lines
 
--
-- Count number of words in a file (like wc -w)
--
wc_w  = interact $ show . length . words
 
--
-- grep lines matching "^foo" from a file
--
grep  = input $ filter (isPrefixOf "foo")
 
--
-- grep lines that don't match "^foo" (grep -v)
--
grep_v= input $ filter (not . isPrefixOf "foo")
 
--
-- number each line of a file
--
num   = input $ zipWith ((. (' ':)) . shows) [1..]
 
--
-- Compute a simple cksum of a file
--
main = interact $ printf "%u\n" . foldl' k 5381
    where k h c = h * 33 + fromIntegral (ord c) :: Int