Ejemplo n.º 1
0
    def compose(self, *others, backwards=False):
        """
        Returns the composition of self with a list of other arrows.

        Parameters
        ----------
        others : list
            Other arrows.
        backwards : bool, optional
            Whether to compose in reverse, default is :code`False`.

        Returns
        -------
        arrow : cat.Arrow
            Such that :code:`arrow == self >> others[0] >> ... >> others[-1]`
            if :code:`backwards` else
            :code:`arrow == self << others[0] << ... << others[-1]`.

        Examples
        --------
        >>> x, y, z = Ob('x'), Ob('y'), Ob('z')
        >>> f, g, h = Box('f', x, y), Box('g', y, z), Box('h', z, x)
        >>> assert Arrow.compose(f, g, h) == f >> g >> h
        >>> assert f.compose(g, h) == Id(x).compose(f, g, h) == f >> g >> h
        >>> assert h.compose(g, f, backwards=True) == h << g << f
        """
        return fold(lambda f, g: f << g if backwards else f >> g, others, self)
 def rec2(nVal: Value, xsVal: Value) -> Value:
     with VNil|xsVal:
         return mnVal
     with VCons|xsVal as (_, l, x, xs):
         return fold(vapp, [l, x, xs, rec2(l, xs)], mcVal)
     with VNeutral|xsVal as (n,):
         return VNeutral(
             NVecElim(evalC(a, env), evalC(m, env), mnVal, mcVal, nVal, n)
         )
     raise TypeError(f"Unknown instance '{type(xsVal)}'")
Ejemplo n.º 3
0
def max_col_widths(xss):
    """
    @return list of max width needed for columns (:: [Int]). see an example below.

    >>> xss = [['aaa', 'bbb', 'cccccccc', 'dd'], ['aa', 'b', 'ccccc', 'ddddddd'], ['aaaa', 'bbbb', 'c', 'dd']]
    >>> max_col_widths(xss)
    [4, 4, 8, 7]
    """
    yss = [[len(x) for x in xs] for xs in xss]
    return fold(curry(zipWith, max), yss[1:], yss[0])
Ejemplo n.º 4
0
def main():
    with open("input") as lines:
        snailfish_numbers = [parse(json.loads(line.strip())) for line in lines]

    result = fold(add, snailfish_numbers)
    print(magnitude(result))
    print(
        max(
            magnitude(add(a, b))
            for a, b in permutations(snailfish_numbers, 2)))
 def rec2(nVal: Value, xsVal: Value) -> Value:
     if isinstance(xsVal, VNil):
         return mnVal
     if isinstance(xsVal, VCons):
         l, x, xs = (xsVal.n, xsVal.x, xsVal.xs)
         return fold(vapp, [l, x, xs, rec2(l, xs)], mcVal)
     if isinstance(xsVal, VNeutral):
         return VNeutral(
             NVecElim(evalC(a, env), evalC(m, env), mnVal, mcVal, nVal,
                      xsVal.n))
     raise TypeError(f"Unknown instance '{type(xsVal)}'")
 def rec2(nVal: Value, xsVal: Value) -> Value:
     with _pm:
         xsVal >> VNil
         return mnVal
     with _pm:
         _, l, x, xs = xsVal >> VCons
         return fold(vapp, [l, x, xs, rec2(l, xs)], mcVal)
     with _pm:
         (n, ) = xsVal >> VNeutral
         return VNeutral(
             NVecElim(evalC(a, env), evalC(m, env), mnVal, mcVal, nVal,
                      n))
     raise TypeError(f"Unknown instance '{type(xsVal)}'")
Ejemplo n.º 7
0
def eager_parse(*words, target=Ty('s')):
    """
    Tries to parse a given list of words in an eager fashion.
    """
    result = fold(lambda x, y: x @ y, words)
    scan = result.cod
    while True:
        fail = True
        for i in range(len(scan) - 1):
            if scan[i:i + 1].r != scan[i + 1:i + 2]:
                continue
            cup = Cup(scan[i:i + 1], scan[i + 1:i + 2])
            result = result >> Id(scan[:i]) @ cup @ Id(scan[i + 2:])
            scan, fail = result.cod, False
            break
        if result.cod == target:
            return result
        if fail:
            raise NotImplementedError
def typeI(i: int, c: Context, term: TermI) -> Type:
#    with Ann|term as p:
#        reveal_type(p)
    with Ann|term as (e1,e2):
        typeC(i, c, e2, VStar())
        t = evalC(e2, [])
        typeC(i, c, e1, t)
        return t
    with Free|term as (x,):
        return c[x]
    with App|term as (e1,e2):
        s = typeI(i, c, e1)
        with VPi|s as (v,f):
            typeC(i, c, e2, v)
            return f(evalC(e2, []))
        raise TypeError(f"Illegal application: {e1}({e2})")
    with Star|term:
        return VStar()
    with Pi|term as (p,p1):
        typeC(i, c, p, VStar())
        t = evalC(p, [])
        typeC(
            i + 1, dict_merge({Local(i): t}, c), substC(0, Free(Local(i)), p1), VStar()
        )
        return VStar()
    with Nat|term:
        return VStar()
    with Zero|term:
        return VNat()
    with Succ|term:
        return VNat()
    with NatElim|term as (m,mz,ms,k):
        typeC(i, c, m, VPi(VNat(), lambda _: VStar()))
        mVal = evalC(m, [])
        typeC(i, c, mz, vapp(mVal, VZero()))
        typeC(
            i,
            c,
            ms,
            VPi(VNat(), lambda l: VPi(vapp(mVal, l), lambda _: vapp(mVal, VSucc(l)))),
        )
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        return vapp(mVal, kVal)
    with Vec|term as (a,n):
        typeC(i, c, a, VStar())
        typeC(i, c, n, VNat())
        return VStar()
    with Nil|term as (a,):
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        return VVec(aVal, VZero())
    with Cons|term as (a,k,x,xs):
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, x, aVal)
        typeC(i, c, xs, VVec(aVal, kVal))
        return VVec(aVal, VSucc(kVal))
    with VecElim|term as (a,m,mn,mc,k,vs):
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, m, VPi(VNat(), lambda k: VPi(VVec(aVal, k), lambda _: VStar())))
        mVal = evalC(m, [])
        typeC(i, c, mn, foldl(vapp, mVal, [VZero(), VNil(aVal)]))
        typeC(
            i,
            c,
            mc,
            VPi(
                VNat(),
                lambda l: VPi(
                    aVal,
                    lambda y: VPi(
                        VVec(aVal, l),
                        lambda ys: VPi(
                            foldl(vapp, mVal, [l, ys]),
                            lambda _: foldl(
                                vapp, mVal, [VSucc(l), VCons(aVal, l, y, ys)]
                            ),
                        ),
                    ),
                ),
            ),
        )
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, vs, VVec(aVal, kVal))
        vsVal = evalC(vs, [])
        return fold(vapp, [kVal, vsVal], mVal)
    raise TypeError(f"Unknown instance '{type(term)}'")
def typeI(i: int, c: Context, term: TermI) -> Type:
    check_argument_types()
    if isinstance(term, Ann):
        e1, e2 = term
        typeC(i, c, e2, VStar())
        t = evalC(e2, [])
        typeC(i, c, e1, t)
        return t
    elif isinstance(term, Free):
        x, = term
        return c[x]
    elif isinstance(term, App):
        e1, e2 = term
        s = typeI(i, c, e1)
        if isinstance(s, VPi):
            typeC(i, c, e2, s.v)
            return s.f(evalC(e2, []))
    elif isinstance(term, Star):
        return VStar()
    elif isinstance(term, Pi):
        p, p1 = term
        typeC(i, c, p, VStar())
        t = evalC(p, [])
        typeC(i + 1, dict_merge({Local(i): t}, c),
              substC(0, Free(Local(i)), p1), VStar())
        return VStar()
    elif isinstance(term, Nat):
        return VStar()
    elif isinstance(term, Zero):
        return VNat()
    elif isinstance(term, Succ):
        return VNat()
    elif isinstance(term, NatElim):
        m, mz, ms, k = term
        typeC(i, c, m, VPi(VNat(), lambda _: VStar()))
        mVal = evalC(m, [])
        typeC(i, c, mz, vapp(mVal, VZero()))
        typeC(
            i, c, ms,
            VPi(VNat(),
                lambda l: VPi(vapp(mVal, l), lambda _: vapp(mVal, VSucc(l)))))
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        return vapp(mVal, kVal)
    elif isinstance(term, Vec):
        a, n = term
        typeC(i, c, a, VStar())
        typeC(i, c, n, VNat())
        return VStar()
    elif isinstance(term, Nil):
        a, = term
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        return VVec(aVal, VZero())
    elif isinstance(term, Cons):
        a, k, x, xs = term
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, x, aVal)
        typeC(i, c, xs, VVec(aVal, kVal))
        return VVec(aVal, VSucc(kVal))
    elif isinstance(term, VecElim):
        a, m, mn, mc, k, vs = term
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, m,
              VPi(VNat(), lambda k: VPi(VVec(aVal, k), lambda _: VStar())))
        mVal = evalC(m, [])
        typeC(i, c, mn, foldl(vapp, mVal, [VZero(), VNil(aVal)]))
        typeC(
            i, c, mc,
            VPi(
                VNat(), lambda l: VPi(
                    aVal, lambda y: VPi(
                        VVec(aVal, l), lambda ys: VPi(
                            foldl(vapp, mVal, [l, ys]), lambda _: foldl(
                                vapp, mVal, [VSucc(l),
                                             VCons(aVal, l, y, ys)]))))))
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, vs, VVec(aVal, kVal))
        vsVal = evalC(vs, [])
        return fold(vapp, [kVal, vsVal], mVal)
    raise TypeError(f"Unknown instance '{type(term)}'")
Ejemplo n.º 10
0
def join_strings(listofwords):  # joining list of words
    return fold(lambda item, running_total: item + running_total, listofwords)
Ejemplo n.º 11
0
from functools import reduce as fold

#adding numbers to give a total
total = fold(lambda item, running_total: item + running_total, [1, 2, 3, 4, 5])
print(total)


def join_strings(listofwords):  # joining list of words
    return fold(lambda item, running_total: item + running_total, listofwords)


words = ["Johnson ", "is ", "great"]
joinwords = join_strings(words)
print(joinwords)
Ejemplo n.º 12
0
def lambda_align(data_rectified, query_unrectified, query_rectified,
                 entrypoint_map):
    """
    :param data_rectified:      data path to be aligned to the query
    :param query_unrectified:   query in its simplest triple formulation from the undirected representation
    :param entrypoint_map:      Elements that need to be present as perfect matches within the data
    :return:                    It returns a pair ((a,b), c), where
                                * a, is the data path that was be aligned
                                * b, is the set of the node alignments to the query
                                * c, is the score associated from both the vertex and edge edit distance
    """
    ## First step: check how many paths were aligned
    ## This if a first approximation of the alignments that will still provide us the edge edit distance
    edge_label_align = {}
    query_edge_match = 0
    edge_matches = 0
    while (query_edge_match < len(query_unrectified)):
        noMatch = True
        for i in range(len(data_rectified)):
            ## If I have no more alignments, then I'm done
            if (query_edge_match >= len(query_unrectified)):
                noMatch = False
                break
            ## If the labels do match (I'm going to refine the alignment in the next step)
            if (data_rectified[i][1] == query_rectified[query_edge_match][1]):
                # try:
                #     if (len(data_rectified) == 2) and (data_rectified[0][1] == 'Conflict.Attack_Place') and (data_rectified[1][1] == 'Conflict.Attack_Target'):
                #         print("loco")
                # except:
                #     pass
                noMatch = False
                edge_label_align[query_edge_match] = data_rectified[i]
                query_edge_match += 1
                edge_matches += 1
        if noMatch:
            query_edge_match += 1

    edge_plus_distance = len(data_rectified) - edge_matches
    edge_minus_distance = len(query_unrectified) - edge_matches

    ## Evaluate the node alignment using the distinct variables from the query
    node_align = {
        vertex: set()
        for vertex in set(
            flatten(map(lambda x: [x[0], x[2]], query_unrectified)))
    }
    for query_edge_id in edge_label_align:
        datum_rectified = edge_label_align[query_edge_id]
        variables = query_rectified[query_edge_id]
        node_align[variables[0]].add(datum_rectified[0])
        node_align[variables[2]].add(datum_rectified[2])

    ## Now, evaluating the vertex edit distance.
    ## 1) The vertex key in node_align is not aligned with the path if either its associated value list is empty or the
    ##    entrypoint was not matched with the entrypoint
    vertex_minus_distance = len(
        list(
            filter(
                lambda x: len(x[1]) == 0 or (x[0] in entrypoint_map and len(
                    set.intersection(x[1], entrypoint_map[x[0]])) == 0),
                node_align.items())))

    ## 2) The added vertices are the ones that are more than the parts that are already aligned.
    vertex_plus_distance = fold(
        operator.add,
        map(lambda x: len(x[1]) - 1,
            filter(lambda x: len(x[1]) > 1, node_align.items())), 0)
    ##    In addition to that, I must add the vertices that have not been matched with the element from the query
    for subpath in noneReplace(
            map(lambda x: None
                if x in edge_label_align.values() else x, data_rectified)):
        vertex_plus_distance += len(set(flatten(subpath)[1:-1]))
    ##    In addition to that, I must consider the nodes not aligned with the entrypoint
    #for ep in entrypoint_map:
    #    if (ep in node_align.keys()):
    #        s = set.difference(set(node_align[ep]), {ep})
    #        if (len(s) > 0):
    #            vertex_plus_distance += len(s)
    #        elif ((len(s) == 0) and (ep in entrypoint_map) and (ep not in entrypoint_map[ep])):
    #            vertex_minus_distance += 1

    finalScore = edge_plus_distance + edge_minus_distance + vertex_minus_distance + vertex_plus_distance
    #if (finalScore == 0):
    #    #print ("SCORE="+str()+" --\t"+str(list(map(lambda x: x[1], data_rectified)))+" E+ = "+str(edge_plus_distance)+ " E- = "+str(edge_minus_distance)+ " V+ = "+str(vertex_plus_distance)+" V- ="+str(vertex_minus_distance))
    #if (finalScore == 1):
    #    print("Score of "+str(finalScore)+" for path "+str(data_rectified)+" for cluster "+str(query_rectified))
    return (data_rectified, node_align, finalScore)
Ejemplo n.º 13
0
def typeI(i: int, c: Context, term: TermI) -> Type:
    #    with _pm, Ann|term as p:
    #        reveal_type(p)
    with _pm, term >> Ann as (e1, e2):
        typeC(i, c, e2, VStar())
        t = evalC(e2, [])
        typeC(i, c, e1, t)
        return t
    with _pm, term >> Free as (x,):
        return c[x]
    with _pm, term >> App as (e1, e2):
        s = typeI(i, c, e1)
        with _pm, s >> VPi as (v, f):
            typeC(i, c, e2, v)
            return f(evalC(e2, []))
        raise TypeError(f"Illegal application: {e1}({e2})")
    with _pm, term >> Star:
        return VStar()
    with _pm, term >> Pi as (p, p1):
        typeC(i, c, p, VStar())
        t = evalC(p, [])
        typeC(i + 1, {Local(i): t, **c}, substC(0, Free(Local(i)), p1), VStar())
        return VStar()
    with _pm, term >> Nat:
        return VStar()
    with _pm, term >> Zero:
        return VNat()
    with _pm, term >> Succ:
        return VNat()
    with _pm, term >> NatElim as (m, mz, ms, k):
        typeC(i, c, m, VPi(VNat(), lambda _: VStar()))
        mVal = evalC(m, [])
        typeC(i, c, mz, vapp(mVal, VZero()))
        typeC(
            i,
            c,
            ms,
            VPi(VNat(), lambda l: VPi(vapp(mVal, l), lambda _: vapp(mVal, VSucc(l)))),
        )
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        return vapp(mVal, kVal)
    with _pm, term >> Vec as (a, n):
        typeC(i, c, a, VStar())
        typeC(i, c, n, VNat())
        return VStar()
    with _pm, term >> Nil as (a,):
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        return VVec(aVal, VZero())
    with _pm, term >> Cons as (a, k, x, xs):
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, x, aVal)
        typeC(i, c, xs, VVec(aVal, kVal))
        return VVec(aVal, VSucc(kVal))
    with _pm, term >> VecElim as (a, m, mn, mc, k, vs):
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, m, VPi(VNat(), lambda k: VPi(VVec(aVal, k), lambda _: VStar())))
        mVal = evalC(m, [])
        typeC(i, c, mn, foldl(vapp, mVal, [VZero(), VNil(aVal)]))
        typeC(
            i,
            c,
            mc,
            VPi(
                VNat(),
                lambda l: VPi(
                    aVal,
                    lambda y: VPi(
                        VVec(aVal, l),
                        lambda ys: VPi(
                            foldl(vapp, mVal, [l, ys]),
                            lambda _: foldl(
                                vapp, mVal, [VSucc(l), VCons(aVal, l, y, ys)]
                            ),
                        ),
                    ),
                ),
            ),
        )
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, vs, VVec(aVal, kVal))
        vsVal = evalC(vs, [])
        return fold(vapp, [kVal, vsVal], mVal)
    raise TypeError(f"Unknown instance '{type(term)}'")
def typeI(i: int, c: Context, term: TermI) -> Type:
    #    with _pm, Ann|term as p:
    #        reveal_type(p)
    with _pm:
        e1, e2 = term >> Ann
        typeC(i, c, e2, VStar())
        t = evalC(e2, [])
        typeC(i, c, e1, t)
        return t
    with _pm:
        (x, ) = term >> Free
        return c[x]
    with _pm:
        e1, e2 = term >> App
        s = typeI(i, c, e1)
        with _pm:
            v, f = s >> VPi
            typeC(i, c, e2, v)
            return f(evalC(e2, []))
        raise TypeError(f"Illegal application: {e1}({e2})")
    with _pm:
        term >> Star
        return VStar()
    with _pm:
        p, p1 = term >> Pi
        typeC(i, c, p, VStar())
        t = evalC(p, [])
        typeC(i + 1, dict_merge({Local(i): t}, c),
              substC(0, Free(Local(i)), p1), VStar())
        return VStar()
    with _pm:
        term >> Nat
        return VStar()
    with _pm:
        term >> Zero
        return VNat()
    with _pm:
        term >> Succ
        return VNat()
    with _pm:
        m, mz, ms, k = term >> NatElim
        typeC(i, c, m, VPi(VNat(), lambda _: VStar()))
        mVal = evalC(m, [])
        typeC(i, c, mz, vapp(mVal, VZero()))
        typeC(
            i,
            c,
            ms,
            VPi(VNat(),
                lambda l: VPi(vapp(mVal, l), lambda _: vapp(mVal, VSucc(l)))),
        )
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        return vapp(mVal, kVal)
    with _pm:
        a, n = term >> Vec
        typeC(i, c, a, VStar())
        typeC(i, c, n, VNat())
        return VStar()
    with _pm:
        (a, ) = term >> Nil
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        return VVec(aVal, VZero())
    with _pm:
        a, k, x, xs = term >> Cons
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, x, aVal)
        typeC(i, c, xs, VVec(aVal, kVal))
        return VVec(aVal, VSucc(kVal))
    with _pm:
        a, m, mn, mc, k, vs = term >> VecElim
        typeC(i, c, a, VStar())
        aVal = evalC(a, [])
        typeC(i, c, m,
              VPi(VNat(), lambda k: VPi(VVec(aVal, k), lambda _: VStar())))
        mVal = evalC(m, [])
        typeC(i, c, mn, foldl(vapp, mVal, [VZero(), VNil(aVal)]))
        typeC(
            i,
            c,
            mc,
            VPi(
                VNat(),
                lambda l: VPi(
                    aVal,
                    lambda y: VPi(
                        VVec(aVal, l),
                        lambda ys: VPi(
                            foldl(vapp, mVal, [l, ys]),
                            lambda _: foldl(vapp, mVal, [
                                VSucc(l), VCons(aVal, l, y, ys)
                            ]),
                        ),
                    ),
                ),
            ),
        )
        typeC(i, c, k, VNat())
        kVal = evalC(k, [])
        typeC(i, c, vs, VVec(aVal, kVal))
        vsVal = evalC(vs, [])
        return fold(vapp, [kVal, vsVal], mVal)
    raise TypeError(f"Unknown instance '{type(term)}'")