feat: add random and shuffle.

This commit is contained in:
redxef 2024-12-17 22:19:44 +01:00
parent 81184c23a7
commit f73f501642
Signed by: redxef
GPG key ID: 7DAC3AA211CBD921
2 changed files with 29 additions and 1 deletions

View file

@ -78,6 +78,23 @@ namespace Jellyfin.Plugin.SmartPlaylist.Lisp {
(sort fc list00))) (sort fc list00)))
""" """
); );
this["rand"] = e.eval(
"""
(lambda
(. a)
(cond
((null a) (random))
((null (cdr a)) (% (random) (car a)))
(t (+
(car a)
(%
(random)
(-
(car (cdr a))
(car a)))))))
"""
);
this["shuf"] = new Symbol("shuffle");
} }
} }
@ -114,8 +131,10 @@ namespace Jellyfin.Plugin.SmartPlaylist.Lisp {
public class Builtins : Dictionary<string, Function> { public class Builtins : Dictionary<string, Function> {
private static Dictionary<string, Type?> ResolvedTypes = new Dictionary<string, Type?>(); private static Dictionary<string, Type?> ResolvedTypes = new Dictionary<string, Type?>();
private Random Random;
public Builtins() : base() { public Builtins() : base() {
Random = new Random();
this["atom"] = _atom; this["atom"] = _atom;
this["eq"] = _eq; this["eq"] = _eq;
this["car"] = _car; this["car"] = _car;
@ -146,11 +165,17 @@ namespace Jellyfin.Plugin.SmartPlaylist.Lisp {
this["string<"] = (x) => _cmp((String a, String b) => a < b, x); this["string<"] = (x) => _cmp((String a, String b) => a < b, x);
this["string<="] = (x) => _cmp((String a, String b) => a <= b, x); this["string<="] = (x) => _cmp((String a, String b) => a <= b, x);
this["haskeys"] = _haskeys; this["haskeys"] = _haskeys;
this["getitems"] = _getitems; this["getitems"] = _getitems;
this["invoke"] = _invoke; this["invoke"] = _invoke;
this["invoke-generic"] = _invoke_generic; this["invoke-generic"] = _invoke_generic;
this["random"] = (x) => new Lisp.Integer(Random.Next());
this["shuffle"] = (x) => {
var newx = ((Lisp.Cons) x.First()).ToList().ToArray();
Random.Shuffle<Expression>(newx);
return Lisp.Cons.FromList(newx);
};
} }
private static T _agg<T>(Func<T, T, T> op, IEnumerable<Expression> args) where T : Expression { private static T _agg<T>(Func<T, T, T> op, IEnumerable<Expression> args) where T : Expression {
T agg = (T) args.First(); T agg = (T) args.First();

View file

@ -233,6 +233,9 @@ namespace Tests
Assert.Equal("10", e.eval("(fold (lambda (a b) (+ a b)) 0 (list 1 2 3 4))").ToString()); Assert.Equal("10", e.eval("(fold (lambda (a b) (+ a b)) 0 (list 1 2 3 4))").ToString());
Assert.Equal("(2 3 4 5 6 7)", e.eval("(append (list 2 3 4) (list 5 6 7))").ToString()); Assert.Equal("(2 3 4 5 6 7)", e.eval("(append (list 2 3 4) (list 5 6 7))").ToString());
Assert.Equal("(1 2 3 4 5 6 7)", e.eval("(qsort (lambda (a b) (> a b)) (list 5 4 7 3 2 6 1))").ToString()); Assert.Equal("(1 2 3 4 5 6 7)", e.eval("(qsort (lambda (a b) (> a b)) (list 5 4 7 3 2 6 1))").ToString());
//Assert.Equal("", e.eval("(rand)").ToString());
//Assert.Equal("", e.eval("(shuf (list 0 1 2 3 4 5 6))").ToString());
} }
} }
} }