I want to write a helper function that could return a string list
helper ['Excuse','Me', 'Exit', 'And'] 'Ex'
and this should return
['Excuse','Exit']
I search up and find in Data.List
have the isInfixOf
function could compare two string, but how could I recursive call to find the correct String list
helper :: [String] -> String -> [String]
helper [] _ = []
helper (x:xs) std
| isInfixOf x std == True : helper
CodePudding user response:
You're almost entirely there.
To call helper
on a list ["Excuse", "Me", "Exit", "And"]
named, oh let's say myList
, you'd write:
helper myList "Ex"
Now, when you pattern match that list with x:xs
, xs
is the tail of the list, which is just another list. To call helper
recursively on this, you'd just write helper xs std
.
You do not need tto explicitly compare the return of isInfixOf
to True
. You also need to handle the case where isInfixOf x std
is not true.
helper :: [String] -> String -> [String]
helper [] _ = []
helper (x:xs) std
| isInfixOf x std = x : helper xs std
| otherwise = helper xs std
CodePudding user response:
There is not really a reason to do that with a recursive function. You want to keep elements of a list that fulfill a certain predicate ("Ex"
being an infix of the element). The filter
function does exactly that.
import Data.List (isInfixOf)
helper :: Eq a => [[a]] -> [a] -> [[a]]
helper = flip (filter . isInfixOf)
For example:
helper ["Excuse", "Me", "Exit", "And"] "Ex"
-- ["Excuse","Exit"]