Cut left / right line (and chomp)

I did not find anything about how to delete a line (remove leading / trailing characters) in Haskell, and there is no place to search for such a strip or chomp function (correct me if Im wrong).

What will i do?

+6
source share
4 answers

Take a look at Data.Text . Anything that uses Prelude lists, such as String s, usually works poorly, especially with features like stripR . Some consider this a mistake of the past because it has infected many (otherwise sensible) interfaces with the inefficiency of using singly linked character lists ( String ) for text data.

The functions you are looking for are in order: dropWhile , dropWhileEnd , dropAround , stripStart , stripEnd , strip .

Please note that there is no special function for deletion based on the equality of characters. You really don't get anything from aliasing dropX with a predicate, unless it is used very often, like Data.Char.isSpace .

+8
source

First of all, you should use Text (from the Text package) instead of String , since Text much more efficient.

In addition, Text already has this feature:

 -- Remove leading and trailing white space from a string. strip :: Text -> Text 
+5
source

A more general approach would be to pass the predicate to strip functions, so stripL isSpace could be stripL isSpace for example. to remove all leading spaces.

Then stripL will, however, be just an alias for dropWhile .

To remove the end, a potentially more efficient version uses foldr ,

 stripR :: (a -> Bool) -> [a] -> [a] stripR pred = foldr keepOrDrop [] where keepOrDrop c xs | pred c = case xs of [] -> [] _ -> c:xs | otherwise = c:xs 

which can start creating output without going through the entire list of input data and is effective if there are no long runs of elements satisfying the predicate that it introduces.

+3
source

Here are 3 functions and 3 generated generated functions:

 stripL :: Char -> String -> String stripL x = dropWhile (==x) stripR :: Char -> String -> String stripR x = reverse . stripL . reverse strip :: Char -> String -> String strip x = stripL x . stripR x chompL :: String -> String chompL = stripL ' ' chompR :: String -> String chompR = stripR ' ' chomp :: String -> String chomp = strip ' ' 

What do you think? Is it possible to add such functions to Data.String ?

+1
source

All Articles