Ask Your Question
3

Restricting the domain of a function

asked 2016-10-08 14:19:51 +0100

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
3

answered 2016-10-08 16:05:34 +0100

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

You can also make R a Python decorator.

edit flag offensive delete link more

Comments

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.

Peter Luschny gravatar imagePeter Luschny ( 2016-10-09 10:50:52 +0100 )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

Stats

Asked: 2016-10-08 14:19:51 +0100

Seen: 940 times

Last updated: Oct 08 '16