module Useful where import List ( intersperse, tails ) import Numeric ( readHex ) import Char ( chr ) ------------------------------- -- Really useful functions hex2num :: (Num a) => String -> a hex2num s = let (result, _):_ = readHex s in result toEnv s = let cleanup = replace "; " ";" s in map tuple (split ';' cleanup) tuple :: String -> (String, String) tuple line = case split '=' line of a:b:_ -> (a,b) a:_ -> (a,"") _ -> ("","") -- not good, probably won't happen... tabtuple :: String -> (String, String) tabtuple line = case split '\t' line of a:b:_ -> (a,b) a:_ -> (a,"") _ -> ("","") -- not good, probably won't happen... ------------------------------- -- Titles and tags tagencode s = concat $ intersperse "_" $ map fix (words s) where fix "&" = "N" fix x = x tagdecode s = concat $ intersperse " " $ map unfix (split '_' s) where unfix "N" = "&" unfix x = x ------------------------------- -- Strings split :: Char -> String -> [String] split _ "" = [] split c s = let (l, s') = break (== c) s in l : case s' of [] -> [] (_:s'') -> split c s'' beginsWith [] [] = True beginsWith _ [] = True beginsWith [] _ = False beginsWith (a:aa) (b:bb) | a == b = aa `beginsWith` bb | otherwise = False dropping [] [] = [] dropping [] _ = [] dropping x [] = x dropping s@(a:aa) (b:bb) | a == b = dropping aa bb | otherwise = s -- replace all occurrences of 'this' with 'that' in the string 'str' -- like Python replace replace _ _ [] = [] replace this that str | str `beginsWith` this = let after = (str `dropping` this) in that ++ replace this that after | otherwise = let x:xs = str in x : replace this that xs eat s = replace s "" -- sometimes newlines get out of hand on the end of form POST submissions, -- so trim all the end newlines and add a single newline fixEndingNewlines = reverse . ('\n':) . dropWhile (=='\n') . reverse . filter (/= '\r') endsWith a b = beginsWith (reverse a) (reverse b) a `contains` b = any (`beginsWith` b) $ tails a