From b38db9fdaadf2b9a86be35abe3b050f0ac8fefcf Mon Sep 17 00:00:00 2001 From: Robert Bendun Date: Fri, 28 Oct 2022 16:01:34 +0200 Subject: [PATCH] new builtins: set_oct, pick --- musique/interpreter/builtin_functions.cc | 49 +++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/musique/interpreter/builtin_functions.cc b/musique/interpreter/builtin_functions.cc index 05525c0..1433103 100644 --- a/musique/interpreter/builtin_functions.cc +++ b/musique/interpreter/builtin_functions.cc @@ -764,7 +764,11 @@ static Result builtin_set_len(Interpreter &interpreter, std::vector builtin_set_len(Interpreter &interpreter, std::vector builtin_set_oct(Interpreter &interpreter, std::vector args) +{ + if (auto oct = get_if(args.front())) { + std::vector result; + for (auto &arg : std::span(args).subspan(1)) { + auto arg_result = Try(traverse(interpreter, std::move(arg), [&](Chord &c) { + for (Note ¬e : c.notes) { + note.octave = oct->round().as_int(); + } + })); + result.push_back(std::move(arg_result)); + } + if (result.size() == 1) { + return result.front(); + } else { + return result; + } + } + + return errors::Unsupported_Types_For { + .type = errors::Unsupported_Types_For::Function, + .name = "set_oct", + .possibilities = { + "TODO" + } + }; +} + static Result builtin_duration(Interpreter &interpreter, std::vector args) { auto total = Number{}; @@ -797,6 +830,18 @@ static Result builtin_flat(Interpreter &i, std::vector args) return Try(into_flat_array(i, std::move(args))); } +/// Pick random value from arugments +static Result builtin_pick(Interpreter &i, std::vector args) +{ + static std::mt19937 rnd{std::random_device{}()}; + auto array = Try(flatten(i, std::move(args))); + if (array.empty()) { + return array; + } + std::uniform_int_distribution dist(0, array.size()-1); + return array[dist(rnd)]; +} + /// Shuffle arguments static Result builtin_shuffle(Interpreter &i, std::vector args) { @@ -1093,6 +1138,7 @@ void Interpreter::register_builtin_functions() global.force_define("partition", builtin_partition); global.force_define("permute", builtin_permute); global.force_define("pgmchange", builtin_program_change); + global.force_define("pick", builtin_pick); global.force_define("play", builtin_play); global.force_define("program_change", builtin_program_change); global.force_define("range", builtin_range); @@ -1101,6 +1147,7 @@ void Interpreter::register_builtin_functions() global.force_define("round", apply_numeric_transform<&Number::round>); global.force_define("scan", builtin_scan); global.force_define("set_len", builtin_set_len); + global.force_define("set_oct", builtin_set_oct); global.force_define("shuffle", builtin_shuffle); global.force_define("sim", builtin_sim); global.force_define("sort", builtin_sort);