Skip to content

Instantly share code, notes, and snippets.

@ZenLiuCN
Last active December 4, 2024 06:08
Show Gist options
  • Save ZenLiuCN/903e2ea83a731d024008946f896baf88 to your computer and use it in GitHub Desktop.
Save ZenLiuCN/903e2ea83a731d024008946f896baf88 to your computer and use it in GitHub Desktop.
simple clojure eval
package sample;
import clojure.java.api.Clojure;
import clojure.lang.Compiler;
import clojure.lang.IFn;
import io.vertx.core.json.JsonObject;
import org.jooq.lambda.function.Function3;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
/**
* @author Zen.Liu
* @since 2024-12-04
*/
public interface CljC {
IFn _INIT = Clojure.var("clojure.core/compile");
Function<String, IFn> COMPILE = s -> ((IFn) Compiler.load(new InputStreamReader(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)))));
public static void main(String[] args) throws IOException, ClassNotFoundException {
Function3<JsonObject, String, Object, Object> Act = COMPILE.apply( //language=clojure
"""
(ns some)
(import io.vertx.core.json.JsonObject)
(defn foo3 [a b c]
(.put a b c))
""")::invoke;
var j = JsonObject.of();
for (int i = 0; i < 1000; i++) {
System.out.println(Act.apply(j, "As", "A" + i));
}
System.out.println(j.encodePrettily());
}
}
package sample;
import clojure.java.api.Clojure;
import clojure.lang.IFn;
import java.io.IOException;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.LongSupplier;
/**
* @author Zen.Liu
* @since 2024-12-04
*/
public interface Clj {
Function<String, IFn> VAR = Clojure::var;
Function<String, Object> READ_STRING = Clojure::read;
IFn EVAL = VAR.apply("clojure.core/eval");
Function<String, IFn> PARSE = READ_STRING.andThen(EVAL::invoke).andThen(c -> ((IFn) c));
BiFunction<String,String,Object> ifn=PARSE.apply(
//language=clojure
"""
(defn foo [a b]
(str a "" b))
""")::invoke;
public static void main(String[] args) throws IOException, ClassNotFoundException {
for (int i = 0; i < 100; i++) {
System.out.println(ifn.apply("a"+i,"b"+i));
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>clj</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>4.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.clojure/clojure -->
<dependency>
<groupId>org.clojure</groupId>
<artifactId>clojure</artifactId>
<version>1.12.0</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment