Restricting the domain of a function

Let f be a function {1,2,3,...,n} -> C. What is the most elegant way to restrict this function to an arbitrary subset of {1,2,3,...,n}?

In other words I would like to have an operator R which takes such a function f and a subset S of [n] and returns a function f': S -> C which coincides with f on S.

edit retag close merge delete

Sort by ยป oldest newest most voted

I am not sure whether it is elegant but you can do it in a straightforward way:

sage: def R(f,S):
....:     def f_restricted(s):
....:         if s in S:
....:             return f(s)
....:         else:
....:             raise ValueError, 'Element not in the set'
....:     return f_restricted
....:
sage: g = R(lambda x :  3*x, [1,2,3])
sage: g(2)
6
sage: g(5)
ValueError: Element not in the set


You can also make R a Python decorator.

more

1

OK, thanks. Since the idea is a generalization of python/itertools/islice I thought it might be possible that it was build into some basic data structure or utility of Sage. The idea of a decorator is interesting.

( 2016-10-09 10:50:52 +0200 )edit