I want to write a function search :: String -> Char -> [Int]
that returns the positions of
all occurrences of the second argument in the first. For example:
search "Bookshop" 'o' == [1,2,6]
search "senselessness" 's' == [0,3,7,8,11,12]
How can one use the function zip :: [a] -> [b] -> [(a,b)]
, the function length :: [a] -> Int
, and the term forms [m..n]
and [m..]
in a list comprehension to do this?
I am writing a code for this, and (correct me if I'm wrong) since the output is not binary as a zip one should, the string one should be omitted from the list comprehension and a parallel list comprehension should be used?
CodePudding user response:
No need to call length
. There rarely is, if ever.
search :: (Num b, Eq a, Enum b) => [a] -> a -> [b]
search s char = [ i | (i,c) <- zip [0..] s, c==char]
Testing:
> search "senselessness" 's'
[0,3,7,8,11,12]
As you can see, we draw both i
and c
from the zipped list, use c
in comparison and output i
if the test passes.