Removing a string from a list of strings in Haskell

I have a question regarding Haskell who pounded my brain. I currently need to write a function that removes the line ie "word" from the list of strings ["hi", "today", "word", "Word", "WORD"] returns the list ["hi", "today", "Word", "WORD"] . I cannot use any functions of a higher order and I can use only primitive recursion.

Thinking about the problem, I thought that maybe I can solve it using recursion, in which you look at the start line of the first line if it matches "w" , then compare the next head with the tail and see if it matches "o" . But then I realized that after all this work, you won’t be able to delete the full line of "word" .

My question is, how do I compare an entire line in a list, and not just compare one item at a time with something like: removeWord (x:xs) . Is it possible? Should I write a helper function to help with the solution?

+4
source share
3 answers

Consider the basic case: deleting a word from an empty list will be empty. It can be trivially written like this:

 removeWord [] _ = [] 

Now consider the case when the list is not empty. You match with x:xs . You can use the guard to choose between these two conditions:

  • x is the word you want to delete. ( x == word )
  • x - is not the word that you want to delete. ( otherwise )
+2
source

You do not need an auxiliary function, although you can write it if you want. You basically have 3 conditions:

  • You get an empty list.
  • You get a list whose first element you want to delete.
  • You get a list whose first element is something else.

In other languages, you must do this with an if-else statement set or with a case or cond case . In Haskell, you can do this with guards:

 remove_word_recursive:: String -> [String] -> [String] remove_word_recursive _ [] = [] remove_word_recursive test_word (x:xs) | test_word == x = what in this case? remove_word_recursive test_word (x:xs) = what in default case? 

Fill out the correct result for this function in these two conditions, and you should do it.

I think that what you are looking for is a special case of the function asked for this question in string filters: Haskell is a list of filter strings based on some conditions . Reading some of the discussions on the accepted answer may help you understand more about Haskell.

+3
source

Since you want to remove a list item, this is easy to do with List Consrehension.

 myList = ["hi", "today", "word", "Word", "WORD"] [x | x <- myList, x /= "word"] 

Result:

 ["hi","today","Word","WORD"] 
+2
source

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


All Articles