findWordIndices' :: String -> String -> [Int]
findWordIndices' w = snd . foldl doStuff (0, []) . words
where
doStuff (cur, results) word =
if word == w
then (cur + length word + 1, cur : results)
else (cur + length word + 1, results)
ただし、これはインデックスを逆順で返します。
g>let str = "ababa baab ab bla ab"
str :: [Char]
g>findWordIndices' "ab" str
[18,11]
it :: [Int]
(++)
これは、cons ( ) の代わりに使用することで修正できます(:)
。
findWordIndices'' :: String -> String -> [Int]
findWordIndices'' w = snd . foldl doStuff (0, []) . words
where
doStuff (cur, results) word =
if word == w
then (cur + length word + 1, results ++ [cur])
else (cur + length word + 1, results)
g>let str = "ababa baab ab bla ab"
str :: [Char]
g>findWordIndices'' "ab" str
[11,18]
it :: [Int]