def test_higher_function(self): f = Function('map', lambda f, xs: [f(x) for x in xs], (FunctionType(INT, INT), LIST), LIST) bar = Function('3x', lambda x: 3 * x, INT, INT) self.assertEqual(f(bar, ListValue([1, 2, 3])), ListValue([3, 6, 9])) self.assertEqual(f.type, FunctionType((FunctionType(INT, INT), LIST), LIST)) self.assertEqual(str(f.type), 'F((F(INT, INT), LIST), LIST)')
def test_function(self): f = Function('foo', lambda x: x + 1, INT, INT) ftype = FunctionType(INT, INT) self.assertEqual(f.type, FunctionType(INT, INT)) self.assertEqual(str(f.type), 'F(INT, INT)') self.assertEqual(f(IntValue(1)), IntValue(2)) self.assertEqual(str(f), 'foo') self.assertEqual(f.name, 'foo')
import collections from deepcoder.dsl.function import Function from deepcoder.dsl.types import INT, BOOL, LIST, FunctionType # firstorder functions HEAD = Function('HEAD', lambda xs: xs[0] if xs else None, LIST, INT) TAIL = Function('TAIL', lambda xs: xs[-1] if xs else None, LIST, INT) MINIMUM = Function('MINIMUM', lambda xs: min(xs) if xs else None, LIST, INT) MAXIMUM = Function('MAXIMUM', lambda xs: max(xs) if xs else None, LIST, INT) REVERSE = Function('REVERSE', lambda xs: xs[::-1], LIST, LIST) SORT = Function('SORT', sorted, LIST, LIST) SUM = Function('SUM', sum, LIST, INT) TAKE = Function('TAKE', lambda n, xs: xs[:n], (INT, LIST), LIST) DROP = Function('DROP', lambda n, xs: xs[n:], (INT, LIST), LIST) ACCESS = Function('ACCESS', lambda n, xs: xs[n] if n >= 0 and len(xs) > n else None, (INT, LIST), INT) # lambda functions PLUS1 = Function('+1', lambda x: x + 1, INT, INT) MINUS1 = Function('-1', lambda x: x - 1, INT, INT) TIMES2 = Function('*2', lambda x: x * 2, INT, INT) DIV2 = Function('/2', lambda x: int(x / 2), INT, INT) TIMESNEG1 = Function('*-1', lambda x: -x, INT, INT) POW2 = Function('**2', lambda x: x**2, INT, INT) TIMES3 = Function('*3', lambda x: x * 3, INT, INT) DIV3 = Function('/3', lambda x: int(x / 3), INT, INT) TIMES4 = Function('*4', lambda x: x * 4, INT, INT) DIV4 = Function('/4', lambda x: int(x / 4), INT, INT)