在这里选择合适的设备很重要。
import Data.Char
您可以使用 Prelude 中函数的略微修改版本words
,其定义为:
words :: String -> [String]
words s = case dropWhile isSpace s of
"" -> []
s' -> w : words s'' where (w, s'') = break isSpace s'
它将字符串分解为以空格分隔的单词列表。修改相当于用字符串中的索引标记每个单词。例如:
words' :: String -> [(Int, String)]
words' = go 0
where
go n s = case break (not . isSpace) s of
(_, "") -> []
(ws, s') -> (n', w) : go (n' + length w) s''
where
n' = n + length ws
(w, s'') = break isSpace s'
例如:
> words' "ababa baab ab bla ab"
[(0,"ababa"),(6,"baab"),(11,"ab"),(14,"bla"),(18,"ab")]
现在,编写你的函数findSubstringIndices
变得几乎是微不足道的:
findSubstringIndices :: String -> String -> [Int]
findSubstringIndices text pattern = [i | (i, w) <- words' text, w == pattern]
它有效吗?是的,它确实:
> findSubstringIndices "ababa baab ab bla ab" "ab"
[11,18]