Feb 25 2009
Python to Haskell (String Functions)
I will be updating this as I go… but see also the Wikipedia page on string functions in various languages.
Joining a string list
-- Python: ",".join(lst) -- either... import Data.List intercalate "," lst -- or... import Data.List concat (intersperse "," lst)
Splitting on a string
-- a.split(ss) -- You might need to get Data.List.Split from Cabal import Data.List.Split splitOn ss a -- using regexes import Text.Regex splitRegex (mkRegex ss) a
Does the string start with the prefix?
-- Python: a.startswith(b) import Data.List isPrefixOf b a -- ByteString import Data.ByteString isPrefixOf b a
Does the string end with the suffix?
-- Python: a.endswith(b) import Data.List isSuffixOf b a -- ByteString import Data.ByteString isSuffixOf b a
Does one string contain another?
-- Python: a.find(b) != -1 import Data.List isInfixOf b a -- ByteString import Data.ByteString isInfixOf b a -- ByteString import Data.ByteString findSubstring b a -- returns Just int or Nothing
Reverse a string
-- Python: a[::-1] reverse a -- ByteString import Data.ByteString reverse bs
Access one character
-- Python: a[pos] a !! pos -- slow O(n) -- ByteString import Data.ByteString index a pos
Where does one string contain another?
-- Python: a.find(b) import Data.ByteString findSubstring a b
Replace substrings
-- Python: b = a.replace(src,dest) import Text.Regex b = subRegex (mkRegex src) a dest
Replace regex, calling function on substitution
-- Python: b = re.sub("[0-9]+", lambda x: str(int(x.group(0)) + 1), a)
import Text.Regex (matchRegexAll, mkRegex)
subRegexFn fn re s = concat $ reverse $ sub s []
where sub s accum = case matchRegexAll re s of
Nothing -> s:accum
Just (pre, mid, post, _) -> sub post $ (fn mid):pre:accum
b = subRegexFn (read . (+ 1) . show) "[0-9]+" a
Strip leading/trailing spaces
-- Python: a.strip() import Data.Char (isSpace) trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace
Loop through every line in stdin
-- Python: loop through every line in stdin, applying a function
-- for line in sys.stdin:
-- print fn(line)
let main = interact (unlines . map fn . lines)
-- or...
let main = do { a <- stdin; mapM_ print (map fn (lines a)); }