Stupid Curry Tricks

From HaskellWiki
Revision as of 16:56, 11 October 2009 by Eric Gesell (talk | contribs)

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

This is a useless peice of code that counts and prints the number of times each character in the English alphabet occurs in a string. The most interesting part is the use of currying to generate the counting functions.

--system to show character frequencies in a set of strings
import System.IO
import Data.Char(toLower)

--letters to scan for
letters = ['a'..'z']

--counts the ocurences of a particualr letter
countLetters :: Char -> [Char] -> Int
countLetters target str = length (filter (\c -> c == target) str)

--creates a curryed version of countletters for a particular letter
makeCounter :: Char -> ([Char] -> Int)
makeCounter c = countLetters c

--creates a countLetters funciton for each letter in the alphabet
counters :: [([Char] -> Int)]
counters = map makeCounter letters

frequencies :: [([Char] -> Int)] -> [Char] -> [Int]
frequencies [] _ = []
frequencies (f:fs) cs = (f cs) : frequencies fs cs

freqs :: [Char] -> [(Char, Int)]
freqs cs = zip letters (frequencies counters cs)

prettyPrint :: (Char, Int) -> String
prettyPrint (c, n) = [c] ++ ":" ++ (show n) ++ "\n"

printList :: [(Char, Int)] -> String
printList [] = []
printList ((c, i):frs) = ((c:[]) ++ ": " ++ (show i) ++ "\n") ++ printList frs

--io and main program

--make shiny print statements

main = do
       str <- readFile "hi.txt"
       let out = (freqs (map toLower str))
       putStrLn $ printList out