Search code examples
haskellfold

Foldr applied to just one argument


So I've got the function that will return True if the number n is the result of applying bitwise or to any subsequence of xs :

checkBits xs n = not $ null $ filter (==n) $ map (foldr (.|.) zeroBits) (subsequences xs)

Now the thing I don't get is that the foldr is given (.|.) and zeroBits, but didn't I need another argument for foldr. Like I understand the function of foldr, you apply it to a function, which is in that case (.|.), to a "starting value", which I guess is zeroBits, but what about the t a, which is mentioned in:

Prelude>:t foldr foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b

Is there anything I'm missing? The code above by the way works like it should.


Solution

  • foldr with a "missing" argument returns a function that takes a single argument (the one that was missing).

    You can then proceed to map that function over your subsequences xs (meaning that each of these subsequences is passed to your specialized foldr function as the "missing" argument).

    This is a very common and useful pattern that allows you to create specialized function by fixing a subset of parameters to a more general function.


    In your example, the "specialized function" remains anonymous. If that becomes too hard to read (or the function is useful in many places), you could give it a name.

    --  create a new function that takes the first ten list elements 
    top10 = take 10       -- call take with a "missing parameter"
    
    -- as opposed to
    ten = take 10 myList  -- call take with all parameters to get a list
    

    It may help (or confuse) to think of Haskell functions as only taking a single parameter and returning a function that takes the next parameter (which in turn returns a function that takes the third parameter or a plain result if that was the last one). An expression like take 1 list can then be read as (take 1) list: Call take 1 to obtain a function, then call that function on the list to get the final result.