Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the words that start with a given letter from a list

Tags:

haskell

I am trying to find the words that start with a particular letter from a list of strings. The user will input the list of words and the starting letter. For example, something like:

"table pencil chair desk pen" "p"

So the words that start 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 what letter each word starts with? The type of the function will look like:

--------------Find words Starting with a given letter------------------

findWords :: String -> Char -> [String]
like image 309
Sindu_ Avatar asked Dec 27 '22 06:12

Sindu_


2 Answers

You use filter,

foo string = filter startsWithP (words string)

then you need to define

startsWithP :: String -> Bool

More useful will be the generic variant

startsWith :: String -> Char -> Bool

to be used like "foo" `startsWith` 'f'.

like image 86
Daniel Fischer Avatar answered May 12 '23 22:05

Daniel Fischer


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

like image 43
Rob Agar Avatar answered May 12 '23 23:05

Rob Agar