'I'm looking for an equivalent of 'isInfixOf' to filter an element from a list
I have a list of words (strings) like text = ["hello","world","me"] and I am looking for an equivalent of isInfixOf to filter this list but which should return True only if the word is fully written.
expected output:
>>> hello -> True
>>> hell -> False
text = ["hello world", "hello guys","nice guys"]
word = "hello"
word2 = "hell"
toSplit :: String -> [String]
toSplit = splitWords . dropWhile (==' ')
where
splitWords "" = []
splitWords s =
let word = takeWhile (/=' ') s
(_, rest) = splitAt (length word) s
in word : splitWords (dropWhile (==' ') rest)
output:
*Main> filter (isInfixOf (word)) text["hello world","hello guys"]
*Main> filter (isInfixOf (word2)) text
["hello world","hello guys"]
*Main>
I tried to split the text before, but I have an error:
*Main> newText = map(toSplit) text
*Main> filter (isInfixOf (word2)) newText
<interactive>:77:28: error:
• Couldn't match type ‘[Char]’ with ‘Char’
Expected type: [[Char]]
Actual type: [[String]]
• In the second argument of ‘filter’, namely ‘newText’
In the expression: filter (isInfixOf (word2)) newText
In an equation for ‘it’: it = filter (isInfixOf (word2)) newText
*Main> filter (isInfixOf (word)) newText
<interactive>:78:27: error:
• Couldn't match type ‘[Char]’ with ‘Char’
Expected type: [[Char]]
Actual type: [[String]]
• In the second argument of ‘filter’, namely ‘newText’
In the expression: filter (isInfixOf (word)) newText
In an equation for ‘it’: it = filter (isInfixOf (word)) newText
*Main>
Solution 1:[1]
You need to split each string into a list of words, then check if that list contains the target word. To do this, you can use the function words :: String -> [String]:
containsWord :: String -> String -> Bool
containsWord word = elem word . words
Then you can filter using containsWord word:
> containsWord "hello" "hello world"
True
> containsWord "hell" "hello world"
False
> filter (containsWord "hello") ["hello world", "hello guys", "nice guys"]
["hello world", "hello guys"]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
