ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 09 Oct 2016 03:50:52 -0500Restricting the domain of a functionhttp://ask.sagemath.org/question/35090/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.Sat, 08 Oct 2016 07:19:51 -0500http://ask.sagemath.org/question/35090/restricting-the-domain-of-a-function/Answer by tmonteil for <p>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}?</p>
<p>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.</p>
http://ask.sagemath.org/question/35090/restricting-the-domain-of-a-function/?answer=35091#post-id-35091I 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.
Sat, 08 Oct 2016 09:05:34 -0500http://ask.sagemath.org/question/35090/restricting-the-domain-of-a-function/?answer=35091#post-id-35091Comment by Peter Luschny for <p>I am not sure whether it is elegant but you can do it in a straightforward way:</p>
<pre><code>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
</code></pre>
<p>You can also make <code>R</code> a Python decorator.</p>
http://ask.sagemath.org/question/35090/restricting-the-domain-of-a-function/?comment=35095#post-id-35095OK, 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.Sun, 09 Oct 2016 03:50:52 -0500http://ask.sagemath.org/question/35090/restricting-the-domain-of-a-function/?comment=35095#post-id-35095