[Python-ideas] Predicate Sets
Terry Reedy
tjreedy at udel.edu
Mon Jan 20 01:34:22 CET 2014
On 1/19/2014 6:41 PM, Daniel da Silva wrote:
> Below is a description of a very simple but immensely useful class
> called a "predicate set". In combination with the set and list
> comprehensions they would allow another natural layer of reasoning with
> mathematical set logic in Python.
Sets defined by predicates are usually infinite and mathematical set
logic works fine with such.
> *Overview:*
> Sets in mathematics can be defined by a list of elements without
> repetitions, and alternatively by a predicate (function) that determines
> inclusion. A predicate set would be a set-like class that is
> instantiated with a predicate function that is called to determine ``a
> in the_predicate_set''.
>
> >> myset = predicateset(lambda s: s.startswith('a'))
> >> 'xyz' in myset
> False
> >> 'abc' in myset
> True
> >> len(myself)
> Traceback (most recent call last):
> [...]
> TypeError
This illustrates the problem with the idea. Only containment is really
straightforward. (I am aware that some operations could be implemented
by defining new predicates. To combines sets with predicatesets, the
sets would have to be represented by predicates, as done below.)
> *Example Uses:*
> # Dynamic excludes in searching
> foo_files = search_files('foo', exclude=set(['a.out', 'Makefile']))
> bar_files = search_files('bar', exclude=predicateset(lambda fname: not
> fname.endswith('~'))) # exclude *~
>
> # Use in place of a set with an ORM
> validusernames = predicateset(lambda s: re.match(s, '[a-zA-Z0-9]+'))
I think these examples are backwards. The APIs should accept functions
either in addition to or instead of collections. It is trivial to turn a
collection into a predicate
>>> p = {'a', 'b', 'c'}.__contains__
>>> p('a')
True
>>> p('d')
False
You need realistic examples that use other operations (but not len ;-).
--
Terry Jan Reedy
More information about the Python-ideas
mailing list