Skip to content

Commit e78bef5

Browse files
committed
search more lazily: foldl -> foldr
1 parent f75324b commit e78bef5

1 file changed

Lines changed: 7 additions & 3 deletions

File tree

source_md/modules.md

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -336,9 +336,13 @@ Let's use a fold to implement searching a list for a sublist.
336336

337337
```{.haskell:hs}
338338
search :: (Eq a) => [a] -> [a] -> Bool
339-
search needle haystack =
340-
let nlen = length needle
341-
in foldl (\acc x -> if take nlen x == needle then True else acc) False (tails haystack)
339+
search needle haystack = foldr step False (tails haystack)
340+
where
341+
step segment continue =
342+
if take nlen segment == needle
343+
then True
344+
else continue
345+
nlen = length needle
342346
```
343347

344348
First we call `tails` with the list in which we're searching.

0 commit comments

Comments
 (0)