str = "\\n"
str2 = "Jon 'Maddog' Orwant"
str3 = "\n"
str4 = "Jon \"Maddog\" Orwant"
str5 = "Multiline string must use a backslash at end of line\n\
\and a backslash at beginning of line\n";
str6 = "It is a common practice\n\
\to indent lines\n\
\(the indentation doesn't change the value of the string)\n"
groupNelem n = unfoldr f
where f [] = Nothing
f s = Just (splitAt n s)
fivers = groupNelem 5
s = "This is what you have"
first = take 1 s
start = take 2 $ drop 5 s
rest = drop 13 s
last' = last s
import Text.Regex
s = "This is what you have"
s2 = a ++ "wasn't" ++ drop 2 b
where (a, b) = splitAt 5 s
s3 = subRegex (mkRegex " is ") s " wasn't "
s4 = a' ++ b
where (a, b) = splitAt 5 s
a' = subRegex (mkRegex "is") a "at"
import Text.Regex
import qualified Control.Arrow as Arrow
f = uncurry (++) . Arrow.first subst . splitAt 5
where subst s = subRegex (mkRegex "is") s "at"
import Text.ParserCombinators.Parsec
fromRight (Right v) = v
fromRight v = error ("fromRight: " ++ show v)
parseStr parser s = fromRight $ parse parser "" s
nchars n = count n anyToken
a = "To be or not to be"
b = parseStr (nchars 6 >> nchars 6) a
[b3,c3] = parseStr (sequence [ lookAhead p1, p2 ]) a
where p1 = nchars 6 >> nchars 2
p2 = nchars 3 >> nchars 2
import List
cut2fmt l = zipWith (-) l (1:l)
applyfmt fmt s = l ++ [s']
where (s', l) = mapAccumL f s fmt
f s n = (s',subs)
where (subs,s') = splitAt n s
fmt = cut2fmt [8,14,20,26,30]
l = applyfmt fmt "12345678912345678901234567890123456789"
a = b || c
import Maybe
v1 = fromMaybe "b" $ Just "a"
v2 = fromMaybe "b" $ Nothing
import Control.Monad (mplus)
v1' = (Just "a") `mplus` (Just "b")
v2' = Nothing `mplus` (Just "b")
class Default_val a where
default_val :: a
is_default_val :: a -> Bool
instance Default_val [a] where
default_val = []
is_default_val = null
instance Default_val Num where
default_val = 0
is_default_val = (== 0)
a &&& b = if a.is_default_val then default_val else b
a ||| b = if a.is_default_val then b else a
foo = bar ||| "DEFAULT VALUE"
import Maybe
import System
argv0 = fmap listToMaybe getArgs
dir = fmap (fromMaybe "/tmp") argv0
dir' = fmap (head . (++ ["/tmp"])) getArgs
import Char
i = ord 'e'
c = chr 101
import Text.Printf
printf "Number %d is character %c\n" 101 101
ascii_character_numbers = map ord "sample"
word = map chr ascii_character_numbers
ibm = map (chr . (+ 1) . ord) "HAL"
s = "an apple a day"
msg1 = "unique chars are: " ++ sort (nub s)
msg2 = "sum is " ++ (show $ sum $ map ord $ s)
#!/usr/bin/runghc
import System
import System.IO
import System.Posix
import Text.Regex
any_input [] = getContents
any_input (f:_) = readFile f
main = do (time, args') <- fmap get_time getArgs
s <- any_input args'
hSetBuffering stdout NoBuffering
mapM_ (\c -> putChar c >> usleep (5000 * time)) s
where get_time (x:args)
| (Just [d]) <- matchRegex (mkRegex "^-([0-9]+)") x = (read d, args)
get_time args = (1, args)
string = "Yoda said, \"can you see this?\""
allwords = words string
revwords = unwords (reverse allwords)
revwords = (unwords . reverse . words) string
revwords' = (unwords . reverse . splitRegex (mkRegex " ")) string
import List
import Text.Regex
unfoldr' :: (a -> Maybe (b, a)) -> a -> ([b], a)
unfoldr' f b =
case f b of
Just (a, b') -> let (l, b'') = unfoldr' f b' in (a:l, b'')
Nothing -> ([], b)
splitRegex' :: Regex -> String -> [(String, String)]
splitRegex' re s =
case unfoldr' f s of
(l, "") -> l
(l, s) -> l ++ [(s, "")]
where
f = fmap f' . matchRegexAll re
f' (before, matched, after, _) = ((before, matched), after)
words' = concatMap (\(a,b) -> [a,b]) . splitRegex' (mkRegex "\\s+")
revwords' = (concat . reverse . words') string
word = "reviver";
is_palindrome s = s == reverse s
long_palindromes = fmap (filter (\s -> s == reverse s && length s > 5) . lines) $
readFile "/usr/share/dict/words"
expand_tabs "" = ""
expand_tabs s = foldr1 ((++) . adjust) $ splitRegex (mkRegex "\t") s
where adjust a = a ++ replicate (8 - (length a) `mod` 8) ' '
unexpand = concat . map (reverse . unexp . reverse) . groupNelem 8 where
unexp s = if head s == ' ' && length s == 8
then '\t' : dropWhile (== ' ') s
else s
subRegexOnceWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, _) -> before ++ new matched ++ after
s = subRegexOnceWith (mkRegex "[0-9]+") (show . (* 2) . read) "I am 17 years old"
import Char
s1 = map toUpper "dromedary"
s2 = map toLower s1
s3 = toUpper (head s2) : tail s2
capitalize "" = ""
capitalize (x:xs) = toUpper x : map toLower xs
s4 = map capitalize $ words "thIS is a loNG liNE"
#!/usr/bin/runghc
import System
import System.IO
import Random
import Char
any_input [] = getContents
any_input (f:_) = readFile f
rand :: Int -> Int -> IO Int
rand low high = getStdRandom (randomR (low, high))
randcap :: String -> IO String
randcap = sequence . map f where
f c = fmap (modify_char c) $ rand(1,5)
modify_char c n = (if n == 1 then toUpper else toLower) c
main = do s <- getArgs >>= any_input
randcap s >>= putStr
s = "I have " ++ show (n+1) ++ " guanacos."
var = "your text\n\
\goes here\n"
import Data.List
input = "Folding and splicing is the work of an editor,\
\ not a mere collection of silicon and mobile electrons!"
wrap columns first_indent indent s =
intercalate "\n" $ wgroup (tail first_indent) (words s)
where wgroup current [] = [current]
wgroup current (w : ws) =
if length current + length w + 1 < columns
then wgroup (current ++ " " ++ w) ws
else current : wgroup (indent ++ w) ws
wrap_simple columns s =
intercalate "\n" $ map unwords $ groupWhile pred $ words s
where pred = (<= columns) . sum . map ((+1) . length)
wrap columns first_indent indent s =
first_indent ++ intercalate ("\n" ++ indent) (map unwords $ first : next)
where (first, rest) = spanWhile (pred $ columns - length first_indent) (words s)
next = groupWhile (pred $ columns - length indent) rest
pred width = (<= width) . sum . map ((+1) . length)
spanWhile :: ([a] -> Bool) -> [a] -> ([a],[a])
spanWhile p l = spanWhile' [] l
where spanWhile' seen [] = (seen, [])
spanWhile' seen (x:xs) =
let seen' = seen ++ [x] in
if p seen' then spanWhile' seen' xs else (seen, x:xs)
groupWhile :: ([a] -> Bool) -> [a] -> [[a]]
groupWhile p l = case spanWhile p l of
([], []) -> []
(l', []) -> [l']
(l', rest) -> l' : groupWhile p rest
import Text.Regex
import Char
subRegexWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, _) -> before ++ new matched ++ (subRegexWith re new after)
quoteMeta :: String -> String
quoteMeta = concatMap (\c -> if (isAlphaNum c) then [c] else ['\\', c])
t1 = subRegex (mkRegex $ quoteMeta "^") "foo^bar" "+"
t2 = subRegex (mkRegex $ quoteMeta "${") "${foo}bar" "{"
t3 = subRegexWith (mkRegex "\\$\\{[^}]*\\}") (map toUpper) "${foo}bar}"
trim_beg, trim_end, trim :: String -> String
trim_beg = snd . span isSpace
trim_end = reverse . trim_beg . reverse
trim = trim_end . trim_beg
trimmed = ">" ++ trim "\t `Here' \t \t \n\n\n" ++ "<"
parse_csv :: String -> [String]
parse_csv s = case lex s of
(x, "") -> [x]
(x, xs) -> x : parse_csv xs
where
lex "" = ("", "")
lex (',':xs) = ("",xs)
lex ('"':xs) = (x++x',xs'') where (x,xs') = lexString xs
(x',xs'') = lex xs'
lex (other:xs) = (other:x,xs') where (x,xs') = lex xs
lexString ('"':xs) = ("",xs)
lexString ('\\':c:xs) = ('\\':c:x , xs') where (x,xs') = lexString xs
lexString (c:xs) = (c:x,xs') where (x,xs') = lexString xs
import Text.ParserCombinators.Parsec
fromRight (Right v) = v
fromRight v = error ("fromRight: " ++ show v)
parseStr parser s = fromRight $ parse parser "" s
toList = fmap (\c -> [c])
many_ = fmap concat . many
parse_csv' = parseStr $ (quoted_string <|> raw_string) `sepBy` char ','
where quoted_string = between (char '"') (char '"') (chars_until '"')
raw_string = chars_until ','
chars_until c = many_ (sequence [ char '\\', anyChar ] <|> toList (noneOf [c]))
test_string = "XYZZY,\"\",\"O'Reilly, Inc\",\"Wall, Larry\",\"a \\\"glub\\\" bit,\",5,\"Error, Core Dumped\""
output = concatMap format_it $ zip [0..] (parse_csv test_string)
where format_it (line, s) = show line ++ " : " ++ s ++ "\n"
import List
import Maybe
import Char
import System.Posix.User
soundex name = (chars!!0) : concatMap show codes'
where
chars = map toUpper (filter isAlpha name)
codes = map head $ group $ map letter_to_code chars
codes' = take 3 (filter (/= 0) (tail codes) ++ [0, 0..])
letter_to_code :: Char -> Int
letter_to_code c = snd $ fromJust $ find (\(letters, _) -> c `elem` letters) letters_code
letters_code =
[ ("AEIOUYHW", 0) , ("BFPV", 1) , ("CGJKQSXZ", 2) , ("DT", 3) , ("L", 4) , ("MN", 5) , ("R", 6) ]
errors = filter (\(code,name) -> code /= soundex name)
[ ("H452", "holmes")
, ("A355", "adomomi")
, ("V536", "vonderlehr")
, ("B400", "ball")
, ("S000", "shaw")
, ("J250", "jackson")
, ("S545", "scanlon")
, ("S532", "saintjohn")
, ("K525", "kingsmith")
, ("B331", "booth-davis")
, ("K530", "Knuth")
, ("K530", "Kant")
, ("L300", "Lloyd")
, ("L300", "Ladd")
]
putStr_getLine s = do putStr s
hFlush stdout
getLine
msoundex = do user <- putStr_getLine "Lookup user: "
matching <- fmap (filter $ matches user) getAllUserEntries
mapM_ (putStrLn . format_user) matching
where
matches wanted user = soundex wanted `elem` (map soundex $ userName user : words (userGecos user))
format_user user = userName user ++ ": " ++ userGecos user
is_integer s = catch (do readIO s :: IO Int
putStrLn "is an integer")
(\_ -> putStrLn "is not")
is_integer = isJust . matchRegex (mkRegex "^[+-]?[0-9]+$")
read_maybe s = case reads s of
[ (v, "") ] -> Just v
_ -> Nothing
is_integer s = isJust (read_maybe s :: Maybe Int)
is_float s = isJust (read_maybe s :: Maybe Double)
equal_num n1 n2 accuracy = abs (n1 - n2) < 10 ^^ (-accuracy)
wage = 536
week = 40 * wage
weekwage :: String
weekwage = printf "One week's wage is: $%.2f\n" (week / 100 :: Double)
rounded = round unrounded
a = 0.255 :: Double
b = printf "%.2f" a
t = do putStrLn ("Unrounded: " ++ show a ++ "\nRounded: " ++ b)
printf "Unrounded: %f\nRounded: %.2f\n" a a
a = [3.3, 3.5, 3.7, -3.3]
t = let l = map (\n -> printf "%.1f\t%d\t%d\t%d" (n :: Double) (truncate n :: Int)
(floor n :: Int) (ceiling n :: Int)) a in
putStrLn (unlines $ "number\ttrncate\tfloor\tceiling" : l)
bin2dec :: String -> Integer
bin2dec = foldr (\c s -> s * 2 + c) 0 . reverse . map c2i
where c2i c = if c == '0' then 0 else 1
dec2bin = map i2c . reverse . unfoldr decomp
where decomp n = if n == 0 then Nothing else Just(n `mod` 2, n `div` 2)
i2c i = if i == 0 then '0' else '1'
m1 = putStrLn $ "Infancy is: " ++ unwords (map show [0..2])
m2 = do putStr "Infancy is: "
mapM_ (printf "%d ") [0 :: Int .. 2]
putStrLn ""
m2' = do putStr "Infancy is: "
mapM_ (\n -> putStr $ show n ++ " ") [0 :: Int .. 2]
putStrLn ""
roman n = concat $ reverse $ snd $ mapAccumL transform n sets
where
transform n set = (n `div` 10, roman set (n `mod` 10))
roman (i,v,x) n = l !! n
where l = [ [], [i], [i,i], [i,i,i], [i,v], [v], [v,i], [v,i,i], [v,i,i,i], [i,x] ]
sets = [('I','V','X'), ('X','L','C'), ('C','D','M'), ('M',too_big,too_big)]
too_big = error "roman: number greater than 3999"
arabic = sum . snd . mapAccumL set_sign 0 . map c2i . reverse
where
set_sign max i = if i >= max then (i, i) else (max, -i)
c2i c = case toUpper c of
'I' -> 1; 'V' -> 5; 'X' -> 10; 'L' -> 50
'C' -> 100; 'D' -> 500; 'M' -> 1000
roman_fifteen = roman 15
s1 = "Roman for fifteen is " ++ roman_fifteen
arabic_fifteen = arabic roman_fifteen
s2 = "Converted back, " ++ roman_fifteen ++ " is " ++ show arabic_fifteen
import Random
import Control.Monad (replicateM)
rand :: Int -> Int -> IO Int
rand low high = getStdRandom (randomR (low, high))
n = rand 25 75
random_elt l = do i <- rand 0 (length l - 1)
return (l !! i)
password = replicateM 8 (random_elt chars)
where chars = concat [ ['A'..'Z'], ['a'..'z'], ['0'..'9'], "!@$%^&*" ]
random_elt' l = fmap (l !!) (rand 0 $ length l - 1)
srand = setStdGen . mkStdGen
randfixed = do srand 2
rand 1 10
std_rand :: IO Double
std_rand = getStdRandom (randomR (0,1))
gaussian_rand =
do r1 <- std_rand
r2 <- std_rand
let u1 = 2*r1 - 1
let u2 = 2*r2 - 1
let w = u1*u1 + u2*u2
if w >= 1
then gaussian_rand
else let w2 = sqrt ((-2 * log w) / w) in
return (u2*w2, u1*w2)
mean = 25
sdev = 2
t = do (r, _) <- gaussian_rand
let salary = r * sdev + mean
printf "You have been hired at $%.2f\n" salary
deg2rad d = d * pi / 180
rad2deg r = r * 180 / pi
degree_sine = sin . deg2rad
asin_val = asin 1
acos_val = acos 1
v = log 10
log10 = logBase 10
t = putStrLn $ "log10(10,000)=" ++ log10 10000
sum_product :: Num a => [a] -> [a] -> a
sum_product u v = sum (zipWith (*) u v)
matrix_zipWith f a b = [zipWith f ak bk | (ak,bk) <- zip a b]
add_matrices a b = matrix_zipWith (+)
inner_product :: Num a => [[a]] -> [[a]] -> [[a]]
inner_product a b = mult a (transpose b)
where mult [] _ = []
mult (a_x:a_xs) b = [sum_product a_x bi | bi <- b] : mult a_xs b
a = [ [3, 2, 3]
, [5, 9, 8] ]
b = [ [4, 7]
, [9, 3]
, [8, 1] ]
c = inner_product a b
import Complex
a = 3 :+ 5
b = 2 :+ (-2)
c = a * b
t1 = (realPart c, imagPart c, conjugate c)
d = 3 :+ 4
t2 = sqrt d
hex s = read ("0x" ++ s) :: Integer
oct s = read ("0o" ++ s) :: Integer
hex = fst . head . Numeric.readHex
oct = fst . head . Numeric.readOct
putStr_getLine s = do putStr s
hFlush stdout
getLine
t = do s <- putStr_getLine "Gimme a number in decimal, octal, or hex: "
let n = read s :: Integer
printf "%d %x %o\n" n n n
t' = do permissions <- putStr_getLine "Enter file permission in octal: "
putStrLn $ "The decimal value is " ++ show (oct permissions)
import Data.List
commify = reverse . intercalate "," . groupNelem 3 . reverse
commify' = subRegexOnceWith (mkRegex "[0-9]+") commify
hours = 2
s = "It took " ++ show hours ++ " hour" ++ if hours == 1 then "" else "s"
s2 = printf fmt (hours :: Int) :: String
where fmt = if hours == 1 then "%d hour is enough.\n" else "%d hours are enough.\n"
subRegexMaybe :: Regex -> String -> String -> Maybe String
subRegexMaybe re s repla = do matchRegex re s
Just (subRegex re s repla)
subRegexMany :: [(String, String)] -> String -> Maybe String
subRegexMany regexps s = msum (map try_one regexps)
where try_one (re, repla) = subRegexMaybe (mkRegex re) s repla
noun_plural s = fromMaybe (error "can't get here") (subRegexMany regexps s)
where regexps = [ ("ss$", "sses")
, ("([psc]h)$", "\\1es")
, ("z$", "zes")
, ("ff$", "ffs")
, ("f$", "ves")
, ("ey$", "eys")
, ("y$", "ies")
, ("ix$", "ices")
, ("([sx])$", "\\1es")
, ("(.)$", "\\1s")
]
s = unlines $ map (\s -> "One " ++ s ++ ", two " ++ noun_plural s ++ ".") $ words test_words
where test_words = "fish fly ox \
\species genus phylum \
\cherub radius jockey \
\index matrix mythos \
\phenomenon formula"
#!/usr/bin/runghc
import List
import System
import Text.Printf
encode :: Eq a => [a] -> [(a, Int)]
encode = map (\x -> (head x, length x)) . group
primeFactors n = factor n primes
where factor n (p:ps) | p*p > n = [n]
| n `mod` p /= 0 = factor n ps
| otherwise = p : factor (n `div` p) (p:ps)
primes = 2 : filter ((==1) . length . primeFactors) [3,5..]
main = getArgs >>= mapM_ do_one
where do_one n = printf "%-10s %s\n" n (to_string $ encode $ primeFactors $ read n)
to_string [(_, 1)] = "PRIME"
to_string l = unwords $ map (\(n,power) -> show n ++ to_string_power power) l
to_string_power p = if p == 1 then "" else "**" ++ show p
import Time
date = fmap show getClockTime
localtime = getClockTime >>= toCalendarTime
utc_time = fmap toUTCTime getClockTime
t = do tm <- localtime
putStrLn $ "Today is day " ++ show (ctYDay tm) ++ " of the current year"
import Data.Time
date = getCurrentTime
t = do today <- fmap utctDay getCurrentTime
let (year, _, _) = toGregorian today
let days = diffDays today (fromGregorian year 0 0)
putStrLn $ "Today is day " ++ show days ++ " of the current year"
import Data.Time
import System.Locale (defaultTimeLocale)
t = do tm <- getCurrentTime
let (year, month, day) = toGregorian (utctDay tm)
printf "The current date is %04d %02d %02d\n" year month day
t2 = do tm <- getCurrentTime
return $ "The current date is " ++ show (utctDay tm)
t3 = fmap (formatTime defaultTimeLocale "%Y-%m-%d") getCurrentTime
import Data.Time
import Data.Time.Clock.POSIX
t = getPOSIXTime
t2 = fmap utcTimeToPOSIXSeconds getCurrentTime
import System.Time
import Data.Time
import Data.Time.Clock.POSIX
epoch = 111111
t1 = posixSecondsToUTCTime epoch
t2 = timeToTimeOfDay (utctDayTime t1)
import Data.Time
ten_seconds_before = addUTCTime (-10)
t = do now <- getCurrentTime
return (now, ten_seconds_before now)
ten_seconds_before (UTCTime day time) = UTCTime day (time - 10)
ten_seconds_before t = t { utctDayTime = utctDayTime t - 10 }
birth_date = fromGregorian 1973 1 18
t = "Nat was 55 days old on: " ++ show (addDays 55 birth_date)
import Data.Time
import Data.Time.Clock.POSIX
bree = UTCTime (fromGregorian 1981 6 16) (timeOfDayToTime $ TimeOfDay 4 35 25)
nat = UTCTime (fromGregorian 1973 1 18) (timeOfDayToTime $ TimeOfDay 3 45 50)
bree' = read "1981-06-16 04:35:25" :: UTCTime
nat' = read "1973-01-18 03:45:50" :: UTCTime
difference = diffUTCTime bree nat / posixDayLength
t = "There were " ++ (show $ round difference) ++ " days between Nat and Bree"
toFloat n = realToFrac n :: Float
t2 = printf "There were %.2f days between Nat and Bree" (toFloat difference) :: String
import Data.Time
import Data.Time.Calendar.MonthDay
import Data.Time.Calendar.OrdinalDate
import Locale
(year, month, day) = (1981, 6, 16)
t = do printf "%d/%d/%d was a %s\n" year month day week_day_name
printf "%d/%d/%d was day %d of the week %d\n" year month day week_day week
printf "%d/%d/%d was day %d of month %d\n" year month day month_day month_
printf "%d/%d/%d was day %d of year %d\n" year month day year_day year_
where date = (fromGregorian year month day)
(week, week_day) = sundayStartWeek date
(_, month_, month_day) = toGregorian date
(year_, year_day) = toOrdinalDate date
(week_day_name, _) = wDays defaultTimeLocale !! week_day
import Data.Time
import Data.Time.Format
import Data.Time.Clock.POSIX
import Locale
day :: Day
day = readTime defaultTimeLocale "%F" "1998-06-03"
epoch = utcTimeToPOSIXSeconds (UTCTime day 0)
epoch_ = utcTimeToPOSIXSeconds (readTime defaultTimeLocale "%F" "1998-06-03")
import Data.Time
import Data.Time.Clock.POSIX
import Text.Regex
day = fromGregorian (read year) (read month) (read day)
where Just [year, month, day] = matchRegex (mkRegex "(.*)-(.*)-(.*)") "1998-06-03"
import Data.Time
import Data.Time.Format
import Locale
t = do now <- getCurrentTime
return $ formatTime defaultTimeLocale "The date is %A (%a) %d/%m/%Y" now
import Data.Time
import System.Posix.Unistd
t = do t1 <- getCurrentTime
usleep 100000
t2 <- getCurrentTime
return (diffUTCTime t2 t1)
t = do usleep 3100000
single_level = [ "this", "that", "the", "other" ]
nested = ("this", "that", ["the", "other"])
import Data.Array
listToArray :: [a] -> Array Int a
listToArray l = listArray (0, length l - 1) l
a1 = listToArray l1
l1' = elems a1
import Data.Array.IO
listToIOArray :: [a] -> IO (IOArray Int a)
listToIOArray l = newListArray (0, length l - 1) l
a1 = listToIOArray l1
l1' = a1 >>= getElems
a = [ "quick", "brown", "fox" ]
a' = words "Why are you teasing me?"
l = lines
"The boy stood on the burning deck\n\
\It was as hot as glass."
big_array = do s <- readFile "mydatafile"
return (lines s)
big_array = fmap lines (readFile "mydatafile")
his_host = "www.haskell.org"
host_info = do Right info <- readProcess "nslookup" [his_host] ""
return info
import System
import System.Posix (getProcessID)
t = do id <- getProcessID
system ("ps " ++ show id)
import Data.List
commify_series :: [String] -> String
commify_series [] = ""
commify_series [x] = x
commify_series xs = intercalate ", " (init xs) ++ " and " ++ (last xs)
array = ["red", "yellow", "green"]
s1 = "I have " ++ commify_series array ++ " marbles"
s2 = "I have " ++ concat array ++ " marbles"
s3 = "I have " ++ unwords array ++ " marbles"
what_about_that_list x = unlines
[ "The list now has " ++ show (length x) ++ " elements."
, "The index of the last element is " ++ show (length x - 1) ++ "."
, "Element .3 is`" ++ x!!3 ++ "'."
]
l1 = [ "Crosby", "Stills", "Nash", "Young" ]
l2 = init l1
l3 = take 3 l1
l4 = take 10001 (l1 ++ repeat "")
l4' = l1 ++ replicate (10001 - length l1) ""
resize_list n default_val l = take n (l ++ repeat default_val)
bad_users = filter is_valid_user all_users
t = mapM_ complain bad_users
t' = mapM_ do_it all_users
where do_it user = do usage <- get_usage user
when (usage > max_quota) (complain user)
import System.Environment
import List
t = getEnvironment >>= putStr . format
where format = unlines . map (\(var, val) -> var ++ "=" ++ val) . sort
t = do Right s <- readProcess "who" [] ""
mapM_ putStrLn (filter ("simonpj" `isPrefixOf`) $ lines s)
t = readFile "/etc/fstab" >>= putStr . reverse_words_of_each_line
where reverse_words_of_each_line = unlines . map (unwords . reverse . words) . lines
l = map (-1 +) [1,2,3]
l = [ ("a", [ 0.5, 3 ]), ("b", [ 0, 1 ]) ]
l' = map (\(name, xs) -> (name, map (* 7) xs)) l
l_' = map (Arrow.second $ map (* 7)) l
import qualified Data.Map as Map
m = Map.fromList [ ("a", [ 0.5, 3 ]), ("b", [ 0, 1 ]) ]
m' = Map.map (map (* 7)) m
l = nub [ 1, 1, 2, 2, 3, 3, 3, 5 ]
t = do Right s <- readProcess "who" [] ""
let users = sort $ nub $ map (head . words) $ lines s
putStrLn ("users logged in: " ++ unwords users)
l = [ 1, 2, 4 ] \\ [ 4, 1 ]
xs = [ 1, 1, 2, 3, 3, 4, 5 ]
ys = [ 1, 2, 4 ]
l1 = xs \\ ys
l2 = nub xs \\ ys
l3 = filter (`notElem` ys) xs
import qualified Data.Set as Set
l = filter (`Set.notMember` Set.fromList [ 4, 1 ]) [ 1, 2, 4 ]
s1 = Set.fromList [ 1, 2, 4 ]
s2 = Set.fromList [ 4, 1 ]
s3 = Set.\\ s1 s2
a = [1, 3, 5, 6, 7, 8]
b = [2, 3, 5, 7, 9]
l1 = a `intersect` b
l2 = a `union` b
l3 = a \\ b
l = [ "Time", "Flies" ]
l2 = l ++ [ "An", "Arrow" ]
insertAt n e l = before ++ [e] ++ after
where (before, after) = splitAt n l
l3 = insertAt 2 "Like" l2
replaceAt n e l = before ++ [e] ++ tail after
where (before, after) = splitAt n l
replaceAllAt assoc l = foldr (\(n, e) -> replaceAt n e) l assoc
l4 = replaceAt 0 "Fruit" l3
l5 = replaceAllAt [ (3,"A"), (4,"Banana") ] l4
l3' = listToArray l3
l4' = l3' Array.// [ (0, "Fruit") ]
l5' = l4' Array.// [ (3,"A"), (4,"Banana") ]
l = reverse [1..5]
reverse_sort = reverse . sort
reverse_sort' = sortBy (\a b -> b <=> a)
reverse_sort'' = sortBy (flip (<=>))
l = reverse_sort [3,2,5,1]
(front,array') = splitAt array n
(array',end) = splitAt array (array.length array - n)
(this : that : friends') = [ "Peter", "Paul", "Mary", "Jim", "Tim" ]
beverages = words "Dew Jolt Cola Sprite Fresca"
(beverages', pair) = splitAt (length beverages - 2) beverages
data Employee = Employee { name, position :: String
, salary :: Int } deriving (Show,Eq)
employees = [ Employee { name="Jim", position="Manager", salary=26000 }
, Employee { name="Jill", position="Engineer", salary=24000 }
, Employee { name="Jack", position="Engineer", salary=22000 } ]
(Just engineer) = find ((== "Engineer") . position) employees
s = name engineer ++ " is engineer"
bigs = filter (> 1000000) nums
t = do Right s <- readProcess "who" [] ""
mapM_ putStrLn (filter ("simonpj" `isPrefixOf`) $ lines s)
engineers = [ x | x <- employees, position x == "Engineer"]
engineers' = filter ((== "Engineer") . position) employees
secondary_assistance = filter ((\x -> x >= 26000 && x < 30000) . salary) employees
l1 = sort [100, 3, 20]
l2 = sort ["100", "3", "20"]
l3 = sortBy (comparing (read :: String -> Int)) ["100", "3", "20"]
sortByKey f = map snd . sortBy (comparing fst) . map (\x -> (f x, x))
l3' = sortByKey (read :: String -> Int) ["100", "3", "20"]
data Employee = Employee { name, position :: String
, salary :: Int } deriving (Show,Eq)
employees = [ Employee { name="Jim", position="Manager", salary=26000 }
, Employee { name="Jill", position="Engineer", salary=24000 }
, Employee { name="Jack", position="Engineer", salary=22000 } ]
employee_sorted = sortBy (comparing name) employees
sortByKey f = map snd . sortBy (comparing fst) . map (\x -> (f x, x))
sortByKeyRev f = map snd . sortBy (flip $ comparing fst) . map (\x -> (f x, x))
employee_sorted' = sortByKey name employees
ordered = sortByKey abs [ 1, -3, 2, 6 ]
ordered_rev = sortByKeyRev abs [ 1, -3, 2, 6 ]
names = [ "Azzz", "Za", "Bbbbbbb" ]
sort_by_2nd_char = sortByKey (!! 1) names
sort_by_last_char = sortByKey last names
sort_by_length = sortByKey length names
import Text.Regex
m = readFile "/etc/passwd" >>= (putStr . unlines . sortByKey key . lines)
where key line = case splitRegex (mkRegex ":") line of
(name : _ : uid : gid : _) ->
(read gid :: Int, read uid :: Int, name)
import System.Posix (sleep)
circular = [1,2,3,4,5] ++ circular
m = mapM_ do_it (take 10 circular)
where do_it n = do putStrLn ("Handling process " ++ show n)
sleep 1
rand :: Int -> Int -> IO Int
rand low high = getStdRandom (randomR (low, high))
randomPermute :: [a] -> IO [a]
randomPermute [] = return []
randomPermute xs =
do n <- rand 0 (length xs - 1)
let (a, e : b) = splitAt n xs
ab <- randomPermute (a ++ b)
return $ e : ab
l = randomPermute [1..5]
make_columns :: Int -> [String] -> [String]
make_columns screen_width mylist =
map concat $ transpose $ groupNelem rows $ map pad_it mylist
where maxlen = maximum(map length mylist) + 1
cols = max 1 (screen_width `div` maxlen)
rows = 1 + (length mylist `div` cols)
pad_it s = take maxlen (s ++ repeat ' ')
getTerminalSize :: IO (Maybe (Int, Int))
getTerminalSize =
do Right s <- readProcess "resize" ["-u"] ""
let vars = parse_shell_vars s
return $ do x <- lookup "COLUMNS" vars
y <- lookup "LINES" vars
return (read x, read y)
where parse_shell_vars = catMaybes . map break_it . lines
break_it s = case break (== '=') s of
(_, "") -> Nothing
(var, _:val) -> Just (var, if last val == ';' then init val else val)
main = do size <- getTerminalSize
let width = maybe 80 fst size
interact (unlines . make_columns width . words)
permutations [] = [[]]
permutations (x:xs) = [zs | ys <- permutations xs, zs <- interleave x ys ]
where interleave x [] = [[x]]
interleave x (y:ys) = [x:y:ys] ++ map (y:) (interleave x ys)
t = mapM_ (putStrLn . unwords) $ permutations $ words "man bites dog"
age = [ ("Nat", 24)
, ("Jules", 25)
, ("Josh", 17) ]
Just jules_age = lookup "Jules" age
import qualified Data.Map as Map
age = Map.fromList [ ("Nat", 24)
, ("Jules", 25)
, ("Josh", 17) ]
jules_age' = age' Map.! "Jules"
age1 = Map.empty
age2 = Map.insert "Nat" 24 age1
age3 = Map.insert "Jules" 25 age2
age4 = Map.insert "Josh" 17 age3
food_color = [ ("Apple" , "red")
, ("Banana", "yellow")
, ("Lemon" , "yellow")
, ("Carrot", "orange") ]
food_color' = Map.fromList food_color
food_color2 = ("Raspberry", "pink") : food_color
t = putStrLn $ "Know foods: " ++ unwords (map fst food_color2)
food_color3 = ("Raspberry", "red") : food_color2
food_color2' = Map.insert "Raspberry" "pink" food_color'
t' = putStrLn $ "Know foods: " ++ unwords (Map.keys food_color2')
food_color3' = Map.insert "Raspberry" "red" food_color2'
s = map describe ["Banana", "Martini"]
where describe name = name ++ " is a " ++ kind name ++ "."
kind name = if isJust (lookup name food_color) then "food" else "drink"
s' = map describe ["Banana", "Martini"]
where describe name = name ++ " is a " ++ kind name ++ "."
kind name = if Map.member name food_color' then "food" else "drink"
food_color2 = filter ((/= "Banana") . fst) food_color
print_foods foods = do putStrLn $ "Keys: " ++ (unwords $ map fst foods)
putStrLn $ "Values: " ++ (unwords $ map snd foods)
before = print_foods food_color
after = print_foods food_color2
food_color2' = Map.delete "Banana" food_color'
print_foods' foods = do putStrLn $ "Keys: " ++ (unwords $ Map.keys foods)
putStrLn $ "Values: " ++ (unwords $ Map.elems foods)
before' = print_foods' food_color'
after' = print_foods' food_color2'
food_color3' = foldr Map.delete food_color' [ "Banana", "Apple", "Cabbage" ]
t = map (\(food, color) -> food ++ " is " ++ color) food_color
t2 = map (\(food, color) -> food ++ " is " ++ color) $ sort food_color
t' = map (\(food, color) -> food ++ " is " ++ color) $ Map.assocs food_color'
t2' = map format_it $ sort $ Map.assocs food_color'
where format_it (food, color) = food ++ " is " ++ color
t2' = map format_it $ sort $ Map.keys food_color'
where format_it food = food ++ " is " ++ food_color' Map.! food
#!/usr/bin/runghc
import System
import Maybe
import List
any_input [] = getContents
any_input (f:_) = readFile f
get_senders = catMaybes . map get_sender
where get_sender line = if prefix `isPrefixOf` line
then Just (drop (length prefix) line)
else Nothing
prefix = "From: "
main = do s <- getArgs >>= any_input
let senders = group $ sort $ get_senders (lines s)
mapM_ (putStrLn . format_it) $ senders
where format_it froms@(name:_) = name ++ ": " ++ show (length froms)
s = show food_color
t = putStrLn s
s2 = map (\(food, color) -> food ++ " => " ++ color) food_color
lookupAll k = map snd . filter ((== k) . fst)
color_to_foods color = map fst $ filter ((== color) . snd) food_color
yellow_food = color_to_foods "yellow"
food_of_color = map (\color -> (color, color_to_foods color)) colors
where colors = nub (map snd food_color)
yellow_food_ = fromMaybe [] (lookup "yellow" food_of_color)
assocListGroupByKey :: Ord a => [(a,b)] -> [(a,[b])]
assocListGroupByKey = map factorize . groupBy same_key . sortBy (comparing fst)
where factorize l@((user, _) : _) = (user, map snd l)
same_key (a,_) (b,_) = a == b
food_of_color = assocListGroupByKey food_color
food_of_color' = foldl (\l (v, k) -> Map.alter (add_it v) k l) Map.empty food_color
where add_it val prev = Just (Set.insert val $ fromMaybe Set.empty prev)
yellow_food' = food_of_color' Map.! "yellow"
t = do Right s <- readProcess "who" [] ""
let l = assocListGroupByKey $ map (parse_it . words) (lines s)
mapM_ (putStrLn . format_it) l
where format_it l (user, ttys) = user ++ ": " ++ unwords ttys
parse_it (user : tty : _) = (user, tty)
surname = [ ("Mickey", "Mantle"), ("Babe", "Ruth") ];
first_name = map swap surname
swap (a,b) = (b,a)
Just name = lookup "Mantle" first_name
t = map (\(food, color) -> food ++ " is " ++ color) $ sort food_color
t2 = map (\(food, color) -> food ++ " is " ++ color) $ sortByKey (length . snd) food_color
t' = map format_it $ sort $ Map.assocs food_color'
where format_it (food, color) = food ++ " is " ++ color
t_' = map format_it $ sort $ Map.keys food_color'
where format_it food = food ++ " is " ++ food_color' Map.! food
drink_color = [ ("Galliano", "yellow"), ("Mai Tai", "blue") ]
ingested_color = drink_color ++ food_color
drink_color' = Map.fromList drink_color
ingested_color' = Map.union drink_color' food_color'
citrus_color = [ ("Lemon", "yellow"), ("Orange", "orange"), ("Lime", "green") ]
common = food_color ++ citrus_color
nubByKey f = nubBy (\a b -> f a == f b)
common_ = nubByKey fst common
non_citrus = food_color \\ citrus_color
citrus_color' = Map.fromList citrus_color
common' = Map.union food_color' citrus_color'
non_citrus' = Map.difference food_color' citrus_color'
name = mapM open_files [ "/etc/termcap", "/etc/passwd", "/bin/cat" ]
where open_files file = do fh <- openFile file ReadMode
return (fh, file)
t = do files <- fmap (map snd) name
putStrLn $ "open files: " ++ intercalate ", " files
t2 = name >>= mapM_ display_size
where display_size (fh, file) =
do size <- hFileSize fh
printf "%s is %d bytes long.\n" file size
encode :: Eq a => [a] -> [(a, Int)]
encode = map (\x -> (head x, length x)) . group
s = encode $ sort "Apple Banana Lemon"
import Data.List
father = [ ("Cain", "Adam")
, ("Abel", "Adam")
, ("Seth", "Adam")
, ("Enoch", "Cain")
, ("Irad", "Enoch")
, ("Mehujael", "Irad")
, ("Methusael", "Mehujael")
, ("Lamech", "Methusael")
, ("Jabal", "Lamech")
, ("Jubal", "Lamech")
, ("Tubalcain", "Lamech")
, ("Enos", "Seth")
]
upline person = person : parents
where parents = unfoldr (\name -> fmap (\x -> (x,x)) $ lookup name father) person
from_Irad = upline "Irad"
ifNull default_ [] = default_
ifNull _ l = l
downline person = person ++ " begat " ++ (ifNull "Nobody" $ intercalate ", " $ children)
where children = map fst $ filter ((== person) . snd) father
to_Tubalcain = downline "Tubalcain"
to_Adam = downline "Adam"
dir = "/usr/include"
include_free =
do files <- getDirectoryContents dir
let h_files = filter (isSuffixOf ".h") files
file2includes <- mapM get_includes h_files
let files_ = map fst $ filter (not . null . snd) file2includes
return $ files_ \\ (concatMap snd file2includes)
where get_includes h_file = fmap (with_content h_file) (readFile $ dir ++ "/" ++ h_file)
with_content h_file content = (h_file, content_to_includes content)
content_to_includes = catMaybes . map (fmap head . matchRegex regex) . lines
regex = mkRegex "^\\s*#\\s*include\\s*<([^>]+)>"
import Data.Ord (comparing)
import qualified Data.Tree as Tree
dirname_basename file = (if dir == "" then "." else (reverse $ tail dir), reverse base)
where (base, dir) = break (== '/') $ reverse file
dirname = fst . dirname_basename
basename = snd . dirname_basename
duProcessFakedInput =
"11732 groovysoap/lib\n\
\68 groovysoap/src/main/groovy/net/soap\n\
\71 groovysoap/src/main/groovy/net\n\
\74 groovysoap/src/main/groovy\n\
\77 groovysoap/src/main\n\
\9 groovysoap/src/examples\n\
\8 groovysoap/src/examples/groovy\n\
\102 groovysoap/src/test\n\
\202 groovysoap/src\n\
\11966 groovysoap\n"
sortByKeyRev f = map snd . sortBy (flip $ comparing fst) . map (\x -> (f x, x))
dirs_tree :: Tree.Tree (String, Int)
dirs_tree = Tree.unfoldTree get_info (last dir2size)
where get_info (dir, size) =
let subdirs = filter ((== dir) . dirname . fst) dir2size in
((dir, size),
if null subdirs then [] else
sortByKeyRev snd $ subdirs ++ [ (dir ++ "/.", size - sum (map snd subdirs)) ])
dir2size = map ((\(size:dir:_) -> (dir, read size)) . words) $ lines duProcessFakedInput
t = putStr $ Tree.drawTree$ fmap (\(f,s)-> show s ++ " " ++ basename f) dirs_tree
mydraw :: Tree.Tree (String, Int) -> String
mydraw tree = unlines $ drawSubTrees [tree]
where drawSubTrees [] = []
drawSubTrees l@(Tree.Node (_,size_max) _ : _) =
let format = "%" ++ show (length $ show size_max) ++ "s %s" in
let draw_one (Tree.Node (name, size) sub) =
let name' = basename name in
printf format (show size) name' :
map (\s -> printf format "|" (map (\_ -> ' ') name') ++ s) (drawSubTrees sub) in
concatMap draw_one l
t2 = putStr $ mydraw dirs_tree
import Text.Regex.Posix
import Text.Regex.Base
meadow = [ "sheeps are ovine", "Sheeps are ovine"
, "Fine bovines demand fine toreadors."
, "Muskoxen are polar ovibovine species."
, "Grooviness went out of fashion decades ago." ]
t1 = filter (=~ "sheep") meadow
t2 = filter (=~ "\\<ovines?") meadow
ignoreCase = makeRegexOpts (defaultCompOpt .|. compIgnoreCase) defaultExecOpt
t3 = filter (matchTest $ ignoreCase "sheep") meadow
import Data.Maybe
import Text.Regex
t1 = filter (isJust . matchRegex (mkRegex "sheep")) meadow
t2 = filter (isJust . matchRegex (mkRegex "\\<ovines?")) meadow
ignoreCase s = mkRegexWithOpts s True False
t3 = filter (isJust . matchRegex (ignoreCase "sheep")) meadow
import qualified Data.ByteString.Char8 as B
t = filter is_sheep meadow
where is_sheep s = B.isInfixOf (B.pack "sheep") (B.pack s)
s1 = subRegex (mkRegex "o+") "good food" "e"
subRegexWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, _) -> before ++ new matched ++ (subRegexWith re new after)
subRegexOnceWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, _) -> before ++ new matched ++ after
s2 = subRegexOnceWith (mkRegex "o+") (\_ -> "e") "good food"
digits = "123456789";
l = digits =~ "..." :: [String]
allOverlappingMatches re s =
case matchRegexAll re s of
Nothing -> []
Just (before, matched, after, _) -> matched : allOverlappingMatches re (tail matched ++ after)
l = allOverlappingMatches (mkRegex "...") digits
string = "And little lambs eat ivy"
(before, matched, after) = string =~ "l[^s]*s" :: (String, String, String)
s = printf "(%s) (%s) (%s)" before matched after :: String
import Text.Regex
import System.Environment
import System.FilePath.Posix
prog_ = subRegex (mkRegex ".*/") "/etc/foo" ""
prog__ = takeFileName "/etc/foo"
prog = getProgName
manpage = "/usr/man/man3/foo.1"
catpage = subRegexMatchesWith (mkRegex "man([0-9])") (\[n] -> "cat" ++ n) manpage
subRegexMatchesWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, l) -> before ++ new l ++ after
bindirs = [ "/usr/bin", "/bin", "/usr/local/bin" ]
libdirs = map (\s -> subRegex (mkRegex "bin$") s "lib") bindirs
is_pure_alphabetic = isJust . matchRegex (mkRegex "^[A-Za-z]+$")
is_pure_alphabetic_ = all isLetter
some_words = [ "silly", "random!stuff#here", "façade", "tschÃŒÃ", "niño", "ÑÑÑÑкОй" ]
l1 = filter is_pure_alphabetic some_words
l2 = filter is_pure_alphabetic_ some_words
l = words "A text with some\tseparator\n"
re = "#"
++ "(\\w+)"
++ "#"
expand_macro vals = subAllRegexMatchesWith (mkRegex re) get_val
where get_val [s] = fromJust (lookup s vals)
s = expand_macro [ ("foo", "42") ] "blah #foo# blah"
subAllRegexMatchesWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, l) -> before ++ new l ++ (subAllRegexMatchesWith re new after)
fishes = "One fish two fish red fish blue fish"
ignoreCase s = mkRegexWithOpts s True False
allMatches re s =
case matchRegexAll re s of
Nothing -> []
Just (_before, _, after, matches) -> matches : allMatches re after
colors = map head $ allMatches (ignoreCase "(\\w+)\\s+fish\\>") fishes
s1 = printf "The third fish is a %s one." (colors !! 2) :: String
s2 = printf "The third fish is a %s one." color :: String
where Just (_, _, _, [_, color]) =
matchRegexAll (ignoreCase "(\\w+\\s+fish\\s+){2}(\\w+)\\s+fish") fishes
subRegexWithEnv re f env s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, matches) -> before ++ matched' ++ (subRegexWithEnv re f env' after)
where (env', matched') = f env (matched:matches)
s3 = subRegexWithEnv (ignoreCase "(\\w+)(\\s+fish\\>)") f 1 fishes
where f n [verbatim, _, fish] = (n+1, if n == 4 then "sushi" ++ fish else verbatim)
withCountEnv f g s = f (\n val -> (n+1, g n val)) 1 s
subRegexWithCount re = withCountEnv (subRegexWithEnv re)
s3' = subRegexWithCount (ignoreCase "(\\w+)(\\s+fish\\>)") f fishes
where f n [verbatim, _, fish] = if n == 4 then "sushi" ++ fish else verbatim
s4 = case matchRegex (ignoreCase ".*\\<(\\w+)\\s+fish\\>") fishes of
Just [last_fish_color] -> printf "Last fish is %s." last_fish_color
_ -> "Failed!"
#!/usr/bin/runghc
import System
import Text.Regex
main = do s <- getArgs >>= any_input
putStr (strip_tags s)
any_input [] = getContents
any_input (f:_) = readFile f
strip_tags s = subRegex (mkRegexWithOpts "<[^>]*>" False True) s ""
test = "<a>after a\n\
\<bbb\n\
\bbb>after b <c>after c\n"
s = strip_tags test
l1 = fmap lines (readFile filename)
l2 = fmap words (readFile filename)
l3 = fmap (splitRegex $ mkRegex "PATTERN") (readFile filename)
f = splitRegex (mkRegex "^\\.(Ch|Se|Ss)$")
splitRegex' :: Regex -> String -> [(String, String)]
splitRegex' re s =
case unfoldr' f s of
(l, "") -> l
(l, s) -> l ++ [(s, "")]
where
f = fmap f' . matchRegexAll re
f' (before, matched, after, _) = ((before, matched), after)
unfoldr' :: (a -> Maybe (b, a)) -> a -> ([b], a)
unfoldr' f b =
case f b of
Just (a, b') -> let (l, b'') = unfoldr' f b' in (a:l, b'')
Nothing -> ([], b)
unwords_keeping_spaces = splitRegex' (mkRegex "\\s+")
t = unwords_keeping_spaces "a b c \t d"
import Text.Regex
import Text.Regex.Posix
import Data.Maybe
import Text.Printf
import System
any_input [] = getContents
any_input (f:_) = readFile f
main = do s <- getArgs >>= any_input
putStr (unlines $ take 3 $ drop 14 $ lines s)
filterByRange :: (a -> Bool) -> (a -> Bool) -> [a] -> [[a]]
filterByRange _ _ [] = []
filterByRange f_beg f_end l =
let l' = dropWhile (not . f_beg) l in
case break f_end l' of
(before, match : l'') -> (before ++ [match]) : filterByRange f_beg f_end l''
_ -> []
extract_XMP :: [String] -> [[String]]
extract_XMP = filterByRange (=~ "<XMP>") (=~ "</XMP>")
t1 = do s <- readFile "foo.html"
return $ extract_XMP $ lines s
ignoreCase s = mkRegexWithOpts s True False
extract_XMP' = filterByRange (match "<XMP>") (match "</XMP>")
where match re = isJust . matchRegex (ignoreCase re)
t1' = do s <- readFile "foo.html"
return $ extract_XMP' $ lines s
mbox_to_headers = filterByRange (match "^From:?\\s") (match "^$")
where match re = isJust . matchRegex (ignoreCase re)
mail_adresses = concatMap search_in_line
where search_in_line line = (line =~ "[^<>(),;[:space:]]+@[^<>(),;[:space:]]+") :: [String]
t2 = do s <- readFile "mbox"
return $ mail_adresses $ concat $ mbox_to_headers $ lines s
import List
import Data.Maybe
special_chars = ".()+*?[]\\{}$^|"
regex_escape_char :: Char -> String
regex_escape_char c = if elem c special_chars
then ['\\', c]
else [c]
regex_escape :: String -> String
regex_escape = concatMap regex_escape_char
glob_list =
[ ('*', ".*")
, ('?', ".")
, ('[', "[")
, (']', "]") ]
glob_char_to_regexp c = fromMaybe (regex_escape_char c) (lookup c glob_list)
glob2pat = concatMap glob_char_to_regexp
pat = glob2pat "*File.*"
import Data.List
import Data.Maybe
import Text.Regex
popstates = ["CO","ON","MI","WI","MN"]
is_state = isJust . matchRegex re
where re = mkRegex $ "\\<(" ++ intercalate "|" popstates ++ ")\\>"
l = filter is_state [ "xxx", "xx CO xx", "WI", "WIxx" ]
is_state' line = any (\re -> isJust $ matchRegex re line) (map to_regexp popstates)
where to_regexp c = mkRegex $ "\\<" ++ c ++ "\\>"
import Data.Maybe
import Data.List
import Text.Regex.Base
import Text.Regex.Posix
is_valid_pattern :: String -> Bool
is_valid_pattern re = isJust (makeRegexM re :: Maybe Regex)
t = let regexp = "(" in
compile defaultCompOpt defaultExecOpt regexp >>=
(\re -> case re of
Left (_, err) -> error ("bad regexp \"" ++ regexp ++ "\": " ++ err)
Right re -> return re)
import Data.List
levenshtein_basic s t = distance (length s) (length t)
where distance i 0 = i
distance 0 j = j
distance i j = minimum [ distance (i-1) j + 1
, distance i (j-1) + 1
, distance (i-1) (j-1) + (if s!!(i-1)==t!!(j-1) then 0 else 1) ]
levenshtein s t = d
where d = [ [distance m n | n<-[0..length t]] | m<-[0..length s] ]
distance i 0 = i
distance 0 j = j
distance i j = minimum [ d!!(i-1)!!j + 1
, d!!i!!(j-1) + 1
, d!!(i-1)!!(j-1) + (if s!!(i-1)==t!!(j-1) then 0 else 1) ]
levenshtein' sa sb = foldl transform [0..length sa] sb
where
transform xs@(x:xs') c = scanl compute (x+1) (zip3 sa xs xs')
where
compute z (c', x, y) = minimum [y+1, z+1, x + if c == c' then 0 else 1]
amatch percentage s t = levenshtein s t * 100 <= percentage * length s
main = do s <- readFile "/usr/share/dict/words"
print $ filter (amatch 20 "balast") (lines s)
import List
import Text.Regex
import Text.Regex.Posix
import Text.Printf
allMatches re = unfoldr (fmap adjust . matchRegexAll re)
where adjust (_before, _, after, matches) = (matches, after)
unfoldr' :: (a -> Maybe (b, a)) -> a -> ([b], a)
unfoldr' f b =
case f b of
Just (a, b') -> let (l, b'') = unfoldr' f b' in (a:l, b'')
Nothing -> ([], b)
allMatches' re = unfoldr' (fmap adjust . matchRegexAll re)
where adjust (_before, _, after, matches) = (matches, after)
t = allMatches (mkRegex "([0-9]+)") "3,4,5,9,120"
mystr = "The year 1752 lost 10 days on the 3rd of September"
t2 =
let (l, remain) = allMatches' (mkRegex "([0-9]+)") mystr in
let after = remain =~ "\\S+" :: String in
putStr $ unlines $ map (\[n] -> "Found number " ++ n) l ++
[ printf "Found %s after the last number" after ]
import List
import Data.Ord (comparing)
import qualified Data.Array as Array
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Control.Arrow as Arrow
listToArray :: [a] -> Array Int a
listToArray l = Array.listArray (0, length l - 1) l
indexOf subst s = findIndex (subst `isPrefixOf`) (tails s)
groupNelem :: Int -> [a] -> [[a]]
groupNelem n = unfoldr f
where f [] = Nothing
f s = Just (splitAt n s)
sortByKey f = map snd . sortBy (comparing fst) . map (\x -> (f x, x))
sortByKeyRev f = map snd . sortBy (flip $ comparing fst) . map (\x -> (f x, x))
any_input :: [FilePath] -> IO String
any_input [] = getContents
any_input (f:_) = readFile f
subRegexWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, _) -> before ++ new matched ++ (subRegexWith re new after)
subRegexOnceWith re new s =
case matchRegexAll re s of
Nothing -> s
Just (before, matched, after, _) -> before ++ new matched ++ after
rand :: Int -> Int -> IO Int
rand low high = getStdRandom (randomR (low, high))
dirname_basename file = (if dir == "" then "." else (reverse $ tail dir), reverse base)
where (base, dir) = break (== '/') $ reverse file
dirname = fst . dirname_basename
basename = snd . dirname_basename
import System.Process
import System.Exit
import System.IO
import Control.Monad
import Control.Concurrent
import qualified Control.Exception as C
readProcess :: FilePath
-> [String]
-> String
-> IO (Either ExitCode String)
readProcess cmd args input = C.handle (return . handler) $ do
(inh,outh,errh,pid) <- runInteractiveProcess cmd args Nothing Nothing
output <- hGetContents outh
outMVar <- newEmptyMVar
forkIO $ C.evaluate (length output) >> putMVar outMVar ()
errput <- hGetContents errh
errMVar <- newEmptyMVar
forkIO $ C.evaluate (length errput) >> putMVar errMVar ()
when (not (null input)) $ hPutStr inh input
hClose inh
takeMVar outMVar
hClose outh
takeMVar errMVar
hClose errh
hPutStr stderr errput
ex <- C.catch (waitForProcess pid) (\_ -> return ExitSuccess)
return $ case ex of
ExitSuccess -> Right output
ExitFailure _ -> Left ex
where
handler (C.ExitException e) = Left e
handler e = Left (ExitFailure 1)