Ask Your Question

Restricting the domain of a function

asked 2016-10-08 07:19:51 -0500

Peter Luschny gravatar image

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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-10-08 09:05:34 -0500

tmonteil gravatar image

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)
sage: g(5)
ValueError: Element not in the set

You can also make R a Python decorator.

edit flag offensive delete link more



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.

Peter Luschny gravatar imagePeter Luschny ( 2016-10-09 03:50:52 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2016-10-08 07:19:51 -0500

Seen: 103 times

Last updated: Oct 08 '16