Haskell: removing space from a list of strings

Question: Write a function that will remove the leading white space from the string. Example: cutWhitespace [" x","y"," z"]Expected Answer:["x","y","z"]

Here is what I have:

cutWhitespace (x:xs) = filter (\xs -> (xs /=' ')) x:xs

This returns ["x", " y"," z"]when input [" x"," y", " z"]. Why does he ignore the space in the second and third lines and how to fix it?

We are allowed to use higher order functions, so I applied a filter.

+4
source share
3 answers

The reason the OP function cutWhitespaceworks only on the first line is because, due to the priority of the operator, it actually performs this function:

cutWhitespace (x:xs) = (filter (\xs -> (xs /=' ')) x) : xs

, , . filter x, x - ; " x".

" x" , "x":

Prelude> filter (\xs -> (xs /=' ')) " x"
"x"

, cutWhitespace, , , ([" y", " z"]) "x", ["x"," y"," z"].

, , , .. [[Char]].

, (x:xs) [] , .

+5

, , , dropWhile :

deleteLeadingWhitespace = dropWhile (\c -> c == ' ')

, , "". isSpace, Data.Char, .

, , , dropWhile :

map deleteLeadingWhitespace

, , , , , , .

+2

, , , , isSpace :: Char -> Bool. True (' '), ('\n'), ('\r'), ('\t'), ('\v') feed ('\f'). , .

Thus, we can remove the spacing of one line with:

dropWhile isSpace

Where we are in dropWhilesuch a way that all the characters where isSpace.

Then we can match this filter to filter spaces from all lines, for example:

import Data.Char(isSpace)

cutWhitespace = map (dropWhile isSpace)
+2
source

Source: https://habr.com/ru/post/1694333/


All Articles