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)
-- 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
-- Python: a.startswith(b) import Data.List isPrefixOf b a -- ByteString import Data.ByteString isPrefixOf b a
-- Python: a.endswith(b) import Data.List isSuffixOf b a -- ByteString import Data.ByteString isSuffixOf b a
-- 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
-- Python: a[::-1] reverse a -- ByteString import Data.ByteString reverse bs
-- Python: a[pos] a !! pos -- slow O(n) -- ByteString import Data.ByteString index a pos
-- Python: a.find(b) import Data.ByteString findSubstring a b
-- Python: b = a.replace(src,dest) import Text.Regex b = subRegex (mkRegex src) a dest
-- 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
-- Python: a.strip() import Data.Char (isSpace) trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace
-- 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)); }