Trimming excess whitespace
The text obtained from sources may unintentionally include beginning or trailing whitespace characters. When parsing such an input, it is often wise to trim the text. For example, when Haskell source code contains trailing whitespace, the GHC compiler ignores it through a process called lexing. The lexer produces a sequence of tokens, effectively ignoring meaningless characters such as excess whitespace.
In this recipe, we will use built-in libraries to make our own trim
function.
How to do it...
Create a new file, which we will call Main.hs
, and perform the following steps:
Import the
isSpace :: Char -> Bool
function from the built-inData.Char
package:import Data.Char (isSpace)
Write a trim function that removes the beginning and trailing whitespace:
trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace
Test it out within
main
:main :: IO () main = putStrLn $ trim " wahoowa! "
Running the code will result in the following trimmed string:
...