title: Using foldr for search instead of foldl in haskell
body: <p>So I'm reading <a href="http://learnyouahaskell.com/" rel="nofollow">"<em>Learn You A Haskell</em>"</a> and in the <a href="http://learnyouahaskell.com/modules#data-list" rel="nofollow">chapter about modules</a>, there's a definition of a function named search, which checks whether a list contains a sub-list.</p>
  
  <pre><code>my_search :: Eq a =&gt; [a] -&gt; [a] -&gt; Bool
  my_search sub l = 
    let 
      len = length sub
      eqTest = (\acc x -&gt; if take len x == sub then True else acc) 
    in foldl eqTest False $ tails l
  </code></pre>
  
  <p>Now, I wonder why not use <code>foldl'</code> which was mentioned earlier in this chapter, and runs faster:</p>
  
  <pre><code>my_search' :: Eq a =&gt; [a] -&gt; [a] -&gt; Bool
  my_search' sub l = 
    let 
      len = length sub
      eqTest = (\acc x -&gt; if take len x == sub then True else acc) 
    in foldl' eqTest False $ tails l
  
  
  *Main&gt; my_search [10^6,10^6+1] [1..10^7]
  True
  (7.76 secs, 3,197,168,792 bytes)
  
  *Main&gt; my_search' [10^6,10^6+1] [1..10^7]
  True
  (4.53 secs, 2,964,986,352 bytes)
  </code></pre>
  
  <p>Better yet, with a small adjustment, we can use <code>foldr</code> which can also handle infinite lists by short-circuiting.</p>
  
  <pre><code>my_searchr :: Eq a =&gt; [a] -&gt; [a] -&gt; Bool
  my_searchr sub l = 
    let 
      len = length sub
      eqTest = (\x acc -&gt; if take len x == sub then True else acc) 
    in foldr eqTest False $ tails l
  </code></pre>
  
  <p>Looking at the <a href="https://hackage.haskell.org/package/base-4.7.0.0/docs/src/Data-List.html#%5C" rel="nofollow">definition</a> of <code>isInfixOf</code>, I see it's implemented with <code>any</code>, which uses <code>foldr</code>.</p>
  
  <p>Am I missing something or is it better to use <code>foldr</code> in this case?</p>