Difference between revisions of "Stupid Curry Tricks"

From HaskellWiki
Jump to: navigation, search
(Added code for frequency.hs)
(Deleting page that hasn't been edited for over 10 years)
Line 1: Line 1:
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

Revision as of 14:18, 6 February 2021