Esempio n. 1
0
def test_functor_variable():
    ctx = Qit()
    ftype = Functor("f_functor", Int(), (Int(), "x"), (Int(), "y"))

    # functions
    fplus = Function().takes(Int(), "x").takes(Int(), "y").returns(Int())
    fplus.code("return x + y;")

    ftimes = Function().takes(Int(), "x").takes(Int(), "y").returns(Int())
    ftimes.code("return x * y;")

    fmod = Function().takes(Int(), "x").takes(Int(), "y").returns(Int())
    fmod.code("return x % y;")

    # apply function in variable fvar to the given list of pairs
    fvar = ftype.variable("f")
    p = Product((Range(1, 4), "x"), (Range(1, 3), "y"))
    apply_f = Function().takes(p, "p").reads(fvar).returns(Int()).code("""
        return f(p.x, p.y);
    """)
    g = p.iterate().map(apply_f).make_function((fvar, ))

    bind_function = Function().takes(ftype, "f")\
                              .returns(Vector(ftype.return_type))
    bind_function.code("return {{g}}(f);", g=g)
    res = ctx.run(ftype.values(fplus, ftimes, fmod).iterate().map(bind_function))
    assert res == [[2, 3, 4, 3, 4, 5], [1, 2, 3, 2, 4, 6], [0, 0, 0, 1, 0, 1]]
Esempio n. 2
0
def test_basic_functor():
    ctx = Qit()

    f_functor = Functor("f_functor", Int(), (Int(), "x"), (Int(), "y"))
    f = Function("f").takes(Int(), "x").takes(Int(), "y").returns(Int()).code("return x + y;")
    g = Function("g").takes(f_functor, "f")\
                     .takes(Int(), "x")\
                     .takes(Int(), "y")\
                     .returns(Int())
    g.code("return f(x, y);")
    assert ctx.run(g(f_functor.value(f), 3, 4)) == 7

    f_functor = FunctorFromFunction(f)
    assert ctx.run(g(f_functor.value(f), -2, 4)) == 2