Post Reply 
Calling a function with an arbitrary number of arguments
06-13-2019, 08:31 PM
Post: #5
RE: Calling a function with an arbitrary number of arguments
This is the hack I was able to come up with, it will call the function given with as many arguments as dimensions the vector passed after it has.

Code:
#cas
// Calls a function passing a veriable number
// of arguments, contained in the iterable ``args_``.
// example ``vcall(fun1, [a, b, c])`` -> ``fun1(a, b, c)``
vacall(func_, args_):= begin
  local args_sum_, i_;
  local args_sym_;
  purge(args_sym_);
  args_sum_ = 0;
  for i_ from 1 to size(args_) do
    args_sum_ := args_sum_ + args_sym_[i_];
  end;
  args_sum_[1] := func_;
  args_sym_ := args_;
  return eval(args_sum_); 
end;

// Convers an iterable to a sequence
toseq(vec_):= begin
  local func_sym_;
  purge(func_sym_);
  return vacall(func_sym_, vec_)[3];
end;
#end

How does this work? Why do you sum the arguments? Why do you index a sum?
The sum operator is used to construct an instruction that will translate to a function call similar to ``sum(a[1], a[2], a[3])``, originated from ``a[1] + a[2] + a[3]``, the more elements you sum to that expression, the more arguments the function will receive. Some symbolic expressions besides vectors in CAS are indexable, indexing them will return parts of the expression, you can also modify the contents of the expression that way.
Knowing this I created a sum with symbolic values and swapped the ``+`` operator by the function passed, then you can assign the arguments passed to the symbolic arguments used in the addition, before returning the expression we should evaluate it to perform the substitutions.
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Calling a function with an arbitrary number of arguments - fakuivan - 06-13-2019 08:31 PM



User(s) browsing this thread: 1 Guest(s)