Search for words starting with this letter from the list

I am trying to find words that start with a specific letter from a list of lines. The user enters a list of words and a starting letter. For example, something like:

"table pen for pencil" "p"

Values โ€‹โ€‹starting with p should be displayed in this case pen and pencil . My first step is to split the string into a list of strings using the words function. Then how do I find which letter each word begins with? The type of function will look like this:

 --------------Find words Starting with a given letter------------------ findWords :: String -> Char -> [String] 
+4
source share
3 answers

You are using filter ,

 foo string = filter startsWithP (words string) 

then you need to identify

 startsWithP :: String -> Bool 

A more general option would be

 startsWith :: String -> Char -> Bool 

which will be used as "foo" `startsWith` 'f' .

+5
source

Hint # 1: in Haskell, a String is defined as a list of Chars , so all functions of the list are available.

+4
source

Since you really want to know the lines starting with the given line (according to your post), I would use the isPrefixOf function:

 filter ("p" `isPrefixOf`) ["cats", "dogs", "poor boys"] 

The function is in Data.List, as far as I remember.

+1
source

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


All Articles