1 | initial version |
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.