Difference between revisions of "Stupid Curry Tricks"
Jump to navigation
Jump to search
Eric Gesell (talk | contribs) |
Eric Gesell (talk | contribs) (Added code for frequency.hs) |
||
Line 1: | Line 1: | ||
− | This is a useless |
+ | This is a useless piece of code that counts and prints the number of times each character in the English alphabet occurs in a string. This version is hard-coded to read from the file "hi.txt", but it can easily be modified to interact with standard IO or read a file passed on the command line. The most interesting part is the use of currying to generate the counting functions. |
<haskell> |
<haskell> |
||
Line 28: | Line 28: | ||
freqs cs = zip letters (frequencies counters cs) |
freqs cs = zip letters (frequencies counters cs) |
||
+ | --make pretty output |
||
prettyPrint :: (Char, Int) -> String |
prettyPrint :: (Char, Int) -> String |
||
prettyPrint (c, n) = [c] ++ ":" ++ (show n) ++ "\n" |
prettyPrint (c, n) = [c] ++ ":" ++ (show n) ++ "\n" |
||
Line 36: | Line 37: | ||
--io and main program |
--io and main program |
||
− | |||
− | --make shiny print statements |
||
− | |||
main = do |
main = do |
||
str <- readFile "hi.txt" |
str <- readFile "hi.txt" |
Revision as of 17:00, 11 October 2009
This is a useless piece of code that counts and prints the number of times each character in the English alphabet occurs in a string. This version is hard-coded to read from the file "hi.txt", but it can easily be modified to interact with standard IO or read a file passed on the command line. 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)
--make pretty output
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
main = do
str <- readFile "hi.txt"
let out = (freqs (map toLower str))
putStrLn $ printList out