Xpresso
The pythonic way to code in Java.
Install / Use
/learn @WantedTechnologies/XpressoREADME
xpresso
The pythonic way to code in Java.
xpresso is a Java library inspired by Python. It allows a (near) line-into-line rewrite of a Python code into Java. It's also a great way to prototype your algorithms directly in Java.
xpresso implements in Java familiar pythonic methods (e.g., len, enumerate, split/join, slicing) and coding paradigms (e.g., everything is iterable, list comprehensions, generators, lambda expressions, filtering iterables using predicates and modifying them using functions).
xpresso also offers multiple useful tools, usually one-liners, that save developer's time and make the code more readable: x.String, x.Object, x.Function, x.memo, x.WebService, x.MapReduce, x.go, x.timer, x.Json, x.mysql, x.csv and others.
xpresso: less boilerplate, more fun, more work done.
License: [MIT] (https://en.wikipedia.org/wikei/MIT_License).
Usage
import com.wantedtech.common.xpresso.x;
x.print("Hello World!");
Main features
Types similar to pythonic ones
import com.wantedtech.common.xpresso.types.*;
Imports: set, dict, list, tuple, DefaultDict, OrderedDict, Bag, HappyFile, HappySQL
Slicable and iterable str type
str city = x.str("New York City");
x.print(city.slice(4,8));
Console: York
for (String character : city)
x.print(character);
Console: N
e
w
Y
o
r
k
One-line file open
Python:
with open("name.txt","r","utf-8") as f:
#do stuff
xpresso:
try (HappyFile f = x.open("name.txt","r","utf-8")) {
//do stuff
}
Works for write/read/append in both text and binary mode.
As in Python, a file opened for reading in text mode is an Iterable of strings:
Python:
for line in f:
print line
xpresso:
for (String line : f)
x.print(line);
Tuples
Python:
my_car = ("Honda", "red", 2010, True)
xpresso:
tuple myCar = x.tuple("Honda", "red", 2010, true);
Dynamic name assignment to tuple elements:
myCar.name("make","color","year","good");
x.print(myCar.get("good"),myCar.get("make"),myCar.get("year"));
Console: true Honda 2010
If name method has not yet been called, but get(someName) is called for the first time, then the returned value will be get(i), where i is the smallest index of a remaining unnamed element in the tuple. All the subsequent calls for the same value someName, the same element i will be returned by get(someName).
You can also define and use a typed version of tuple. For example:
tuple3<String,String,Integer> myCar = x.tuple3("Honda", "red", 2010);
String myCarMake = myCar.left;
String myCarColor = myCar.middle;
Integer myCarYear = myCar.right;
tuple2<String,tuple3<String,String,Integer>> item = x.tuple2("car",myCar);
String type = item.key; //or, alternatively String type = item.left;
tuple3<String,String,Integer> car = item.value; //or, alternatively tuple3<String,String,Integer> car = item.right;
Neat standard object creation
Python:
trips = ["Dubai","New York","London","Paris","Moscow","London","Saint-Petersburg","New York"]
russian_cities = set(["Moscow","Saint-Petersburg"])
rank = dict(("Moscow":30),("Saint-Petersburg":15),("New York":20),("London":10),("Paris":5),("Dubai":32))
xpresso:
list<String> trips = x.list("Dubai","New York","London","Paris","Moscow","London","Saint-Petersburg","New York");
set<String> russianCities = x.set("Moscow","Saint-Petersburg");
dict<Integer> rank = x.dict(x.tuple("Moscow",30),x.tuple("Saint-Petersburg",15),x.tuple("New York",20),x.tuple("London",10),x.tuple("Paris",5),x.tuple("Dubai",32));
Functions and predicates
import com.wantedtech.common.functional.*
Function<Object, String> toUpperCaseFun = new Function<Object, String>() {
public String apply(Object value) {
return value.toString().toUpperCase();
}
};
list<String> tripsUp = x.map(toUpperCaseFun, trips);
x.print(tripsUp);
Console: [DUBAI, NEW YORK, LONDON, PARIS, MOSCOW, LONDON, SAINT-PETERSBURG, NEW YORK]
Predicate<Object> containsO = new Predicate<Object>() {
public Boolean apply(Object value) {
return x.String("o").in(value.toString()) ? true : false;
}
};
list<String> tripsO = x.filter(containsO, trips);
x.print(tripsO);
Console: [New York, London, Moscow, London, New York]
You don't need to define a new Function class every time you want to transform an iterable in a certain way. You can use the x.Function that automagically wraps any static method of any Java class into a Function:
Function<String,String> myUpper = x.Function(String.class, "toUpperCase");
iterable = x.map(myUpper, iterable);
The x.Function method can also wrap static methods that take several arguments:
Function<tuple3<String,Integer,Boolean>,Double> mySomeFunc = x.Function(Some.class, "someStaticMethod");
Function<tuple3<String,Integer,Boolean>,Double> myOtherFunc = x.Function(Other.class, "someOtherMethod");
Function<tuple3<String,Integer,Boolean>,Double> funcToUse;
if (someCondition) {
funcToUse = mySomeFunc;
} else {
funcToUse = myOtherFunc;
}
double sum;
for (element : iterable) {
sum += funcToUse.apply(x.tuple3(element,intParam,boolParam));
}
If in a certain class there're more than one static method with the same name, you need to specify which one of them you want to wrap by providing parameter types:
Function<tuple3<String,Integer,Boolean>,Double> mySomeFunc = x.Function(Some.class, "someStaticMethod", String.class, Integer.class, Boolean.class);
Lambda expressions
Python:
best_cities = reversed(sorted(item for item in rank.items(),lambda x: x[0]))
xpresso:
list<String> bestCities = x.reverse(x.sort(yield().forEach(rank.items()),x.lambdaF("x: x[0]")));
More complex lambda expressions:
Predicate<Object> pr = x.lambdaP("x : f0(f1(x[1])) == '''new york'''",x.lower,x.strip);
Function<Object,Integer> squareFun = x.lambdaF("x : x * x");
Function<Object,Integer> fun = x.lambdaF("x : x[0] * 10 * (x[1] - f0(x[2])))",squareFun);
Function chains:
Function<Object,Integer> incrementFun = x.lambdaF("x : x + 1");
Function<Object,Integer> squareFun = x.lambdaF("x : x * x");
Function<Object,Integer> chainFun = x.chain(incrementFun,squareFun);
chainFun will first increment, then square its input. x.chain(...) can take more than two functions as argument. The last function in the chain has to return the value of the desired output type.
List comprehensions
Python:
foreign_trips_lower = [city.lower() for city in trips if city not in russian_cities]
xpresso:
list<String> foreignTripsLower = x.list(x.<String>yield().apply(x.lower).forEach(trips).unless(x.in(russianCities)));
Python:
cool_cities = dict([(city.upper(),true) for (city, score) in rank.items() if score > 5])
xpresso:
dict<Integer> coolCities = x.dict(x.yield("city","_").apply(x.upper).replace(true).where("city","score").in(rank.items()).when(x.lambdaP("city, score : score > 20")));
Python:
evals = [True if value == "good" else False for value in some_list]
xpresso:
list<Boolean> evals = x.list(x.<Boolean>yield().replace(true).when(x.lambdaP("x : x == '''good'''")).replaceOtherwise(false).forEach(someList));
You can use list comprehensions to extract properties from element objects:
class PlannedTrip {
int year;
String city;
public PlannedTrip(int year, String city) {
this.year = year;
this.city = city;
}
public int getYear() { return year; }
public String getCity() { return city; }
}
list<PlannedTrip> plans = x.list(new PlannedTrip(2015, "Moscow"), new PlannedTrip(2016, "Paris"));
list<tuple> plansData = x.list(x.yield("year", "city").where("year", "city").in(plans));
x.print(plansData);
Console: [(2015, Moscow), (2016, Paris)]
You can also filter the extracted values in the same expression:
list<tuple> plansData = x.list(x.yield("year", "city").where("year", "city").in(plans).when(x.lambdaP("year, city : year > 2015)));
x.print(plansData);
Console: [(2016, Paris)]
RESTful web services
Let's suppose we have an object of a class SomeMath which has two methods we would like to publish on the network as RESTful web services, getSum and getProduct:
public class SomeMath() {
public Double getSum(Double[] values) { //we want to publish this one
return x.sum(values);
}
public Double getProduct(Double x, Double y) {//and this one
return x * y;
}
public Double anotherMethod(Double somethingElse) {//but not this one
return somethingElse;
}
}
In order to convert our SomeMath class into a web service, we simply need to first annotate our two methods we want to call from the network with the @ExposeAs annotation, and then start our web service:
public class SomeMath() {
public Double getSum(@ExposeAs("values") Double[] values) {
return x.sum(values);
}
public Double getProduct(@ExposeAs("x") Double x, @ExposeAs("y") Double y) {
return x * y;
}
public Double anotherMethod(Double somethingElse) {
return somethingElse;
}
}
WebService ws = x.WebService(new SomeMath(), 8080).start();
That's all! Our web service is up and running. Let's test it. Open the following url in your browser:
http://localhost:8080/SomeMath/getSum?values=5&values=6&values=7
The output:
18.0
Now open the following url:
http://localhost:8080/SomeMath/getProduct?x=5&y=10
The output:
50.0
If a method returns an output type of more complex classes such as Java's standard Map and List, or xpresso's own list and dict, the output will be a corresponding JSON string.
Generators
Python:
def firstn(n):
num = 0
while num < n:
yield num
num += 1
for i in firstn(500000):
print i
xpresso:
public Generator<Integer> firstn (final int n)
