by wis · 2y ago · 0 comments
Here's the usage example from the README:
from leopards import Q
l = [{"name":"John","age":"16"}, {"name":"Mike","age":"19"},{"name":"Sarah","age":"21"}]
filtered= Q(l,{'name__contains':"k", "age__lt":20})
print(list(filtered))
Versus: [x for x in l if ('k' in x['name'] and int(x['age']) < 20)]
Outputs: [{'name': 'Mike', 'age': '19'}]
Also from the readme: > Even though, age was str in the dict, as the value of in the query dict was int, Leopards converted the value in dict automatically to match the query data type. This behaviour can be stopped by passing False to convert_types parameter.
I don't like this default behavior. filtered = Q(l,{'name__contains':"k", "age__lt":20})
Verus: filtered = [x for x in l if ('k' in x['name'] and int(x['age']) < 20)] {"name" (includes? "k"), "age" (< 20)}
into {"name" #(includes? % "k"), "age" #(< % 20)}
which is the same as {"name" (fn [name] (includes? name "k")), "age" (fn [age] (< age 20))}
Then have another macro that converts that into the pattern matching code, or maybe there's already something in the standard library.You could serialize the patterns using EDN as a substitute for JSON.
Fun stuff.
I wrote something [similar][1] in javascript. With that it would be:
const is_k_kid = tisch.compileFunction((etc) => ({
'name': name => name.includes('k'),
'age': age => age < 20,
...etc
}));
const result = input.filter(is_k_kid);
Yes, "...etc" is part of the DSL.