Search in sources :

Example 1 with Fun

use of primal.fp.Funs.Fun in project suite by stupidsing.

the class CompileProverImpl method prover.

@Override
public Prove_ prover(Node node) {
    var rt = f.input();
    Fun<FunExpr, ProveRt> cf = cps -> FunCreator.of(ProveRt.class, false).create(rt_ -> cps).apply(Map.ofEntries());
    var compiled = new Object() {

        private FunExpr compile_(Node node, FunExpr cps) {
            return new // 
            SwitchNode<FunExpr>(// 
            node).matchArray(".0, .1", m -> {
                return compile_(m[0], compile_(m[1], cps));
            }).matchArray(".0; .1", m -> {
                FunExpr cps1;
                if (Boolean.TRUE) {
                    var proveRt_ = cf.apply(cps);
                    cps1 = f.object(proveRt_).invoke("test", rt);
                } else
                    cps1 = cps;
                FunExpr f0 = compile_(m[0], cps1);
                FunExpr f1 = compile_(m[1], cps1);
                return f.seq(f0, f1);
            }).matchArray("fail", m -> {
                return f._void();
            }).matchArray("yes", m -> {
                return cps;
            }).nonNullResult();
        }
    }.compile_(node, rt.fieldSet("ok", ok));
    var proveRt = cf.apply(compiled);
    return proverCfg -> {
        var rt_ = new Runtime_();
        rt_.proverCfg = proverCfg;
        proveRt.test(rt_);
        return rt_.ok;
    };
}
Also used : Map(java.util.Map) Fun(primal.fp.Funs.Fun) FunCreator(suite.jdk.gen.FunCreator) ProverFactory(suite.lp.doer.ProverFactory) SwitchNode(suite.node.io.SwitchNode) FunExpr(suite.jdk.gen.FunExpression.FunExpr) ProverCfg(suite.lp.Configuration.ProverCfg) FunFactory(suite.jdk.gen.FunFactory) Node(suite.node.Node) SwitchNode(suite.node.io.SwitchNode) Node(suite.node.Node) SwitchNode(suite.node.io.SwitchNode) FunExpr(suite.jdk.gen.FunExpression.FunExpr)

Example 2 with Fun

use of primal.fp.Funs.Fun in project suite by stupidsing.

the class ScrapeHtml method parse.

public HtmlNode parse(String in) {
    var pairs = new ArrayList<IntRange>();
    int pos0, posx = 0;
    nextTag: while (0 <= (pos0 = in.indexOf("<", posx))) if ((posx = pos0 + 1) < in.length() && !Is.whitespace(in.charAt(posx)))
        if (0 <= (posx = in.indexOf(">", posx))) {
            pairs.add(IntRange.of(pos0, ++posx));
            if (in.startsWith("<![CDATA[", pos0)) {
                posx = in.indexOf("]]>", pos0 + 9);
                continue nextTag;
            }
            for (var rawTextTag : List.of("script", "style", "textarea", "title")) if (in.startsWith(rawTextTag, pos0 + 1)) {
                posx = in.indexOf("</" + rawTextTag, posx);
                continue nextTag;
            }
        } else
            break;
    Fun<String, IntObjPair<String>> getNameFun = tag -> {
        int p1 = 1, px = tag.length() - 1;
        var first = tag.charAt(p1);
        var last = tag.charAt(px - 1);
        int d;
        if (first == '!')
            return IntObjPair.of(0, null);
        else {
            if (first == '/') {
                p1++;
                d = -1;
            } else if (last == '/') {
                px--;
                d = 0;
            } else
                d = 1;
            var ps = 0;
            while (ps < px && !Is.whitespace(tag.charAt(ps))) ps++;
            var name = tag.substring(p1, ps);
            return IntObjPair.of(d, name);
        }
    };
    var deque = new ArrayDeque<>(List.of(new HtmlNode(null, "", 0, 0)));
    IntIntSink addTextFun = (prevp, p0) -> {
        if (prevp != p0) {
            var s = htmlUtil.decode(in.substring(prevp, p0)).trim();
            if (!s.isEmpty())
                deque.element().children.add(new HtmlNode(null, s, prevp, p0));
        }
    };
    var prevp = 0;
    for (var pair : pairs) {
        var htmlNode = deque.element();
        var p0 = pair.s;
        var px = pair.e;
        addTextFun.sink2(prevp, p0);
        var tag = in.substring(p0, px);
        prevp = getNameFun.apply(tag).map((d, name) -> {
            if (d == -1) {
                // closing tag
                HtmlNode hn;
                while (!deque.isEmpty()) if (Equals.string(getNameFun.apply((hn = deque.pop()).tag).v, name)) {
                    hn.p2 = p0;
                    hn.px = px;
                    break;
                }
            } else {
                // opening tag
                var htmlNode1 = new HtmlNode(name, tag, p0, px);
                htmlNode.children.add(htmlNode1);
                if (d == 1)
                    deque.push(htmlNode1);
            }
            return px;
        });
    }
    addTextFun.sink2(prevp, in.length());
    return deque.pop();
}
Also used : Pair(primal.adt.Pair) PerMap(primal.persistent.PerMap) IntRange(primal.primitive.adt.IntRange) Build(primal.Verbs.Build) IntIntSink(primal.primitive.IntIntSink) Predicate(java.util.function.Predicate) Fun(primal.fp.Funs.Fun) Set(java.util.Set) Assoc(primal.parser.Operator.Assoc) Read(primal.MoreVerbs.Read) Is(primal.Verbs.Is) ArrayList(java.util.ArrayList) Streamlet(primal.streamlet.Streamlet) List(java.util.List) Split(primal.MoreVerbs.Split) Substring(primal.Verbs.Substring) ArrayDeque(java.util.ArrayDeque) Equals(primal.Verbs.Equals) IntObjPair(primal.primitive.adt.pair.IntObjPair) IntIntSink(primal.primitive.IntIntSink) IntObjPair(primal.primitive.adt.pair.IntObjPair) ArrayList(java.util.ArrayList) ArrayDeque(java.util.ArrayDeque)

Example 3 with Fun

use of primal.fp.Funs.Fun in project suite by stupidsing.

the class InterpretFunLazy0 method inferType.

public Node inferType(Node node) {
    class InferType {

        private PerMap<String, Node> env;

        private InferType(PerMap<String, Node> env) {
            this.env = env;
        }

        private Node infer(Node node) {
            return new // 
            SwitchNode<Node>(// 
            node).match("define .0 := .1 ~ .2", (a, b, c) -> {
                var tv = new Reference();
                var i1 = new InferType(env.put(Atom.name(a), tv));
                bind(infer(b), tv);
                return i1.infer(c);
            }).match("if .0 then .1 else .2", (a, b, c) -> {
                var tr = new Reference();
                bind(Suite.parse("BOOLEAN"), infer(a));
                bind(tr, infer(b));
                bind(tr, infer(c));
                return tr;
            }).match(".0 => .1", (a, b) -> {
                var tp = new Reference();
                var env1 = env.replace(Atom.name(a), tp);
                return Suite.substitute("FUN .0 .1", tp, new InferType(env1).infer(b));
            }).match(".0_{.1}", (a, b) -> {
                var tr = new Reference();
                bind(Suite.substitute("FUN .0 .1", infer(b), tr), infer(a));
                return tr;
            }).applyTree((op, l, r) -> {
                var tr = new Reference();
                var tl = Suite.substitute("FUN .0 FUN .1 .2", infer(l), infer(r), tr);
                bind(tl, env.getOrFail(op.name_()));
                return tr;
            }).applyIf(Atom.class, a -> {
                return env.getOrFail(a.name);
            }).applyIf(Int.class, a -> {
                return Suite.parse("NUMBER");
            }).applyIf(Node.class, a -> {
                return Atom.NIL;
            }).nonNullResult();
        }

        private boolean bind(Node t0, Node t1) {
            return Binder.bind(t0, t1) ? true : fail();
        }
    }
    var env0 = // 
    PerMap.<String, Node>empty().put(Atom.TRUE.name, // 
    Suite.parse("BOOLEAN")).put(Atom.FALSE.name, // 
    Suite.parse("BOOLEAN")).put(BaseOp.AND___.name, // 
    Suite.substitute("FUN .0 FUN .1 CONS .0 .1")).put(ERROR.name, // 
    new Reference()).put(FST__.name, // 
    Suite.substitute("FUN (CONS .0 .1) .0")).put(SND__.name, Suite.substitute("FUN (CONS .0 .1) .1"));
    var env1 = // 
    Read.from2(// 
    TreeUtil.boolOperations).keys().fold(env0, (e, o) -> e.put(o.name_(), Suite.substitute("FUN NUMBER FUN NUMBER BOOLEAN")));
    var env2 = // 
    Read.from2(// 
    TreeUtil.intOperations).keys().fold(env1, (e, o) -> e.put(o.name_(), Suite.substitute("FUN NUMBER FUN NUMBER NUMBER")));
    return new InferType(env2).infer(node);
}
Also used : PerMap(primal.persistent.PerMap) Reference(suite.node.Reference) Suite(suite.Suite) BaseOp(suite.node.io.BaseOp) Fail.fail(primal.statics.Fail.fail) Fun(primal.fp.Funs.Fun) Iterate(primal.fp.Funs.Iterate) Read(primal.MoreVerbs.Read) Node(suite.node.Node) Atom(suite.node.Atom) Mutable(primal.adt.Mutable) Binder(suite.lp.doer.Binder) SwitchNode(suite.node.io.SwitchNode) Int(suite.node.Int) TreeUtil(suite.node.util.TreeUtil) Reference(suite.node.Reference) Node(suite.node.Node) SwitchNode(suite.node.io.SwitchNode) PerMap(primal.persistent.PerMap) Atom(suite.node.Atom)

Example 4 with Fun

use of primal.fp.Funs.Fun in project suite by stupidsing.

the class Trade_ method dividend.

public static float dividend(Streamlet<Trade> trades, Fun<String, LngFltPair[]> fun, Dbl_Dbl feeFun) {
    var sum = 0f;
    for (var pair : Read.fromMultimap(trades.toMultimap(trade -> trade.symbol))) {
        var dividends = fun.apply(pair.k);
        var puller = Puller.of(pair.v);
        LngIntPair tn = LngIntPair.of(0l, 0);
        Source<LngIntPair> tradeSource = () -> {
            var trade = puller.pull();
            var t = trade != null ? Time.of(trade.date + " 12:00:00").epochSec(8) : Long.MAX_VALUE;
            return LngIntPair.of(t, tn.t1 + (trade != null ? trade.buySell : 0));
        };
        var tn1 = tradeSource.g();
        for (var dividend : dividends) {
            while (tn1 != null && tn1.t0 < dividend.t0) {
                tn.update(tn1.t0, tn1.t1);
                tn1 = tradeSource.g();
            }
            var amount = tn.t1 * dividend.t1;
            sum += amount - feeFun.apply(amount);
        }
    }
    return sum;
}
Also used : Union(primal.Verbs.Union) Math.log1p(java.lang.Math.log1p) Fun(primal.fp.Funs.Fun) Math_(suite.math.Math_) HashMap(java.util.HashMap) LngFltPair(primal.primitive.adt.pair.LngFltPair) Math.abs(java.lang.Math.abs) Obj_Flt(primal.primitive.FltPrim.Obj_Flt) Dbl_Dbl(primal.primitive.Dbl_Dbl) Streamlet_.forInt(suite.util.Streamlet_.forInt) ArrayList(java.util.ArrayList) Streamlet(primal.streamlet.Streamlet) Map(java.util.Map) Math.expm1(java.lang.Math.expm1) Valuation(suite.trade.Account.Valuation) Pair(primal.adt.Pair) IntFltPair(primal.primitive.adt.pair.IntFltPair) IntIntSink(primal.primitive.IntIntSink) Source(primal.fp.Funs.Source) Set(java.util.Set) Math.min(java.lang.Math.min) Read(primal.MoreVerbs.Read) LngIntPair(primal.primitive.adt.pair.LngIntPair) List(java.util.List) Eod(suite.trade.data.DataSource.Eod) AsInt(primal.primitive.fp.AsInt) Math.max(java.lang.Math.max) Math.floor(java.lang.Math.floor) Equals(primal.Verbs.Equals) Puller(primal.puller.Puller) LngIntPair(primal.primitive.adt.pair.LngIntPair)

Example 5 with Fun

use of primal.fp.Funs.Fun in project suite by stupidsing.

the class NioClusterMapTest method testClusterMap.

@Test
public void testClusterMap() throws IOException {
    var nNodes = 3;
    var peers = forInt(nNodes).map2(i -> "NODE" + i, i -> new InetSocketAddress(localHost, 3000 + i)).toMap();
    var clusters = // 
    Read.from2(// 
    peers).keys().map2(name -> name, // 
    name -> ex(() -> new NioCluster(name, peers))).toMap();
    for (var cluster : clusters.values()) cluster.start();
    var peerNames = new ArrayList<>(peers.keySet());
    var clMap = // 
    Read.from2(// 
    peers).keys().map2(name -> name, // 
    name -> new NioClusterMap<Integer, String>(clusters.get(name))).toMap();
    Sleep.quietly(5 * 1000);
    System.out.println("=== CLUSTER FORMED (" + LocalDateTime.now() + ") ===\n");
    Source<NioClusterMap<Integer, String>> peerf = () -> clMap.get(peerNames.get(random.nextInt(nNodes)));
    Int_Obj<Sink<Runnable>> setf = i -> cont -> peerf.g().set(i, Integer.toString(i), v0 -> cont.run(), fail);
    Int_Obj<Sink<Runnable>> getf = i -> cont -> peerf.g().get(i, v -> {
        assertEquals(Integer.toString(i), v);
        cont.run();
    }, fail);
    Fun<NioCluster, Sink<Runnable>> closef = cluster -> cont -> {
        try {
            cluster.stop();
            System.out.println("=== CLUSTER STOPPED (" + LocalDateTime.now() + ") ===\n");
        } catch (IOException ex) {
            fail(ex);
        }
        cont.run();
    };
    var sinks = // 
    Streamlet.concat(// 
    forInt(9).map(setf), // 
    forInt(9).map(getf), Read.from2(clusters).values().map(closef)).toList();
    new Object() {

        public void run(int i) {
            if (i < sinks.size())
                sinks.get(i).f(() -> run(i + 1));
        }
    }.run(0);
    Read.from2(clusters).values().map(cluster -> New.thread(cluster::run)).collect(Start::thenJoin);
    for (var cluster : clusters.values()) cluster.close();
}
Also used : NioClusterMap(suite.net.cluster.impl.NioClusterMap) Fail.fail(primal.statics.Fail.fail) Fun(primal.fp.Funs.Fun) Source(primal.fp.Funs.Source) LocalDateTime(java.time.LocalDateTime) IOException(java.io.IOException) Random(java.util.Random) Start(primal.Verbs.Start) New(primal.Verbs.New) Log_(primal.os.Log_) InetSocketAddress(java.net.InetSocketAddress) Sink(primal.fp.Funs.Sink) Read(primal.MoreVerbs.Read) Streamlet_.forInt(suite.util.Streamlet_.forInt) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) Test(org.junit.jupiter.api.Test) Streamlet(primal.streamlet.Streamlet) Rethrow.ex(primal.statics.Rethrow.ex) Rethrow(primal.statics.Rethrow) Int_Obj(primal.primitive.IntPrim.Int_Obj) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Sleep(primal.Verbs.Sleep) NioCluster(suite.net.cluster.impl.NioCluster) NioClusterMap(suite.net.cluster.impl.NioClusterMap) Start(primal.Verbs.Start) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) IOException(java.io.IOException) NioCluster(suite.net.cluster.impl.NioCluster) Sink(primal.fp.Funs.Sink) Test(org.junit.jupiter.api.Test)

Aggregations

Fun (primal.fp.Funs.Fun)9 Node (suite.node.Node)6 Read (primal.MoreVerbs.Read)5 ArrayList (java.util.ArrayList)4 List (java.util.List)3 Map (java.util.Map)3 Pair (primal.adt.Pair)3 Source (primal.fp.Funs.Source)3 Fail.fail (primal.statics.Fail.fail)3 Streamlet (primal.streamlet.Streamlet)3 Set (java.util.Set)2 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)2 Test (org.junit.jupiter.api.Test)2 Split (primal.MoreVerbs.Split)2 Equals (primal.Verbs.Equals)2 Is (primal.Verbs.Is)2 PerMap (primal.persistent.PerMap)2 IntIntSink (primal.primitive.IntIntSink)2 Suite (suite.Suite)2 Generalizer (suite.lp.doer.Generalizer)2