Reputation: 3387
I am learning Parsec
and want to practice it by implementing function trim
. Here is my code:
module Trim where
import Text.ParserCombinators.Parsec hiding(spaces)
trim = reverse.trimFront.reverse.trimFront
trimFront :: String->String
trimFront = readExpr trimParser
readExpr :: Parser String->String->String
readExpr parser input = case parse parser "trim" input of
Left err -> error $ show err
Right val -> val
spaces = many space
trimParser :: Parser String
trimParser = spaces >> many anyChar
my question is, How could I implement trim
in function trimParser
directly without having to implement trimFront
first?
Upvotes: 2
Views: 509
Reputation: 48611
To trim the spaces from both sides of a string:
trim :: String -> String
trim = dropWhileEnd isSpace . dropWhile isSpace
Note that you may be better off using the following implementation of dropWhileEnd
instead of the one from Data.List
, depending on the situation:
dropWhileEnd :: (a -> Bool) -> [a] -> [a]
dropWhileEnd p = foldr
(\x xs -> if null xs && p x then [] else x : xs) []
Upvotes: 2