3 ms·
filter predicate xs :)
by sid0 15y ago
filter predicate xs
:)
- rtperson 15y agoHaskell, I assume. Two things really make Haskell shine when it comes to problems like this: 1) higher-order list operations -- you're not iterating through indices, so there is no possibility for off-by-one errors, and 2) immutability -- your code takes a new list with the undesirable elements removed; you can't remove elements of a structure at the same time you're iterating through it. I always love the problems on SPOJ where they give you the number of cases up front, because in Haskell you can almost always throw out that value. Your map function knows when the list is out of elements.
- sid0 15y agoYeah, I was thinking Haskell, but any functional language will do. Problems like the one in the blog post really make you appreciate them.
- morsch 15y agoThe snippet I posted can easily be made into a generic function<T> that takes a collection<T> and a predicate<T>. For example, the Apache Commons library offers such a function for Java, so where available the code comes down to the fairly similar CollectionUtils.filter(collection, predicate); Of course aside from being a bit more verbose, predicate needs to be an object (often a singleton), because you can't pass around functions.
- wanorris 15y agoIt's not as concise as Haskell, but the addition of FP capabilities to C# make it a lot more pleasant as a practical language than it was in earlier days. var filteredCollection = collection.Where(x => predicate(x));
- sid0 15y agoAs far as I remember you can write that as var filteredCollection = collection.Where(predicate); I agree that C# is a fundamentally usable language.
- MostAwesomeDude 15y agol = [i for i in l if predicate(i)]