any with foldr

myAny :: (a -> Bool) -> [a] -> Bool
myAny f [] = False
myAny f (x:xs) = foldr step False xs
     where step x acc = acc || f x 

I’m beginning to hate type inference. Yes the compiler can figure out the types, but the human (i.e. me) often can’t without running the compiler. Redundancy and verbosity are not bugs. They are features. Human language (e.g. English) is verbose and redundant for good reason. Redundancy helps humans understand.

The source code is not just for the compiler. Otherwise we’d write in machine language. User interface factors need to be considered in the design of programming languages.

5 Responses to “any with foldr”

  1. Anonymous Says:

    I haven’t run it, but I’m pretty sure your definition has a bug: it ignores the first element of the list.

  2. Michael Day Says:

    Right, myAny does not need to do pattern matching on the list, it can just pass it to foldr.
    I agree regarding type inference: explicit type declarations give the programmer a chance to state their intent and act as documentation for those who come after. Type inference for local variables is a big time saver though, especially compared to the classic Java pattern:StupidFactory stupidFactory = new StupidFactory();

  3. Elliotte Rusty Harold Says:

    Yep, it’s buggy. Here’s a fixed version:

    myAny :: (a -> Bool) -> [a] -> Bool
    myAny f [] = False
    myAny f (x:xs) = foldr step (f x) xs
         where step x acc = acc || f x
  4. Anonymous Says:

    What about this?

    myAny :: (a -> Bool) -> [a] -> Bool
    myAny f xs = foldr step False xs
    where step x acc = acc || f x

  5. Matt Says:

    Agreed that there is redundancy that helps humans to understand, but there is redundancy that makes things harder to understand, e.g. Java’s painful constructs like:

    Map<String, List> map = new HashMap<String, List();

    The thing I like about type inference is that I get the option, as a programmer, to give the types when I think it would be most helpful for others reading the program. At the least, in Haskell, it certainly makes a lot of sense (and I believe is a widely adopted best practice?) to annotate at least the top-level functions of a program with explicit types. Something that would help with Haskell is an editor/IDE with the feature that you can highlight any subexpression, and it would show you the inferred type of that subexpression (I don’t know of any, though.)

Leave a Reply