Problem: Given a arbitrary string, split by a given regex and format into an R vector expression. E.g. Convert "a..,b..,c,d" into 'c("a","b","c","d")', when the given regex is "[.,]+".
Solution in haskell:
module Lib
( toRVec
) where
import Data.List (intersperse)
import Data.Maybe (fromMaybe)
import Data.Text ()
import Data.Text (pack, strip, unpack)
import Text.Regex (mkRegex, splitRegex)
(//) :: Maybe a -> a -> a
(//) = flip fromMaybe
stripString = (unpack . strip . pack)
toRVec :: String -> Maybe String -> Maybe Bool -> String
toRVec orig delim' toStrip' =
let
delim = delim' // "[ \n]+"
toStrip = toStrip' // True
ws = splitRegex (mkRegex delim) $ stripString orig
ws1 = map (\w -> "\"" ++ w ++ "\"") $ if toStrip then
map stripString ws
else
ws
ws2 = intersperse "," ws1
res = foldl (++) "" ws2
in "c(" ++ res ++ ")"
Any suggestion for improvements are welcome.