Constant functions

class sage.misc.constant_function.ConstantFunction[source]

Bases: SageObject

A class for function objects implementing constant functions.

EXAMPLES:

sage: f = ConstantFunction(3)
sage: f
The constant function (...) -> 3
sage: f()
3
sage: f(5)
3
>>> from sage.all import *
>>> f = ConstantFunction(Integer(3))
>>> f
The constant function (...) -> 3
>>> f()
3
>>> f(Integer(5))
3

Such a function could be implemented as a lambda expression, but this is not (currently) picklable:

sage: g = lambda x: 3
sage: try:
....:     loads(dumps(g))
....: except Exception as e:
....:     if 'PicklingError' in str(type(e).__name__):
....:         print('PicklingError Caught')
PicklingError Caught
sage: f == loads(dumps(f))
True
>>> from sage.all import *
>>> g = lambda x: Integer(3)
>>> try:
...     loads(dumps(g))
... except Exception as e:
...     if 'PicklingError' in str(type(e).__name__):
...         print('PicklingError Caught')
PicklingError Caught
>>> f == loads(dumps(f))
True

Also, in the long run, the information that this function is constant could be used by some algorithms.

Todo

  • Should constant functions have unique representation?

  • Should the number of arguments be specified in the input?

  • Should this go into sage.categories.maps? Then what should be the parent (e.g. for lambda x: True)?