1

Is it possible to create and send a list of functions as an argument to another function, and then have some functions within this list call other functions in this list?
For example, I want a function that works on a list passed as an argument, and then performs the first function in the list of functions on this list of numbers, and if that function makes calls to other functions within that list, they can be retrieved and used.

e.g.: deviation(Numbers, Functions) -> %Functions = [fun master/1, fun avg/1, fun meanroots/1]
Master calls avg, then passes that result into meanroots, etc. but at the end of the call chain the master is the one that will return a value.

I'd like to know if this is functionally possible, whether within OTP alone or using NIFs, and if there are samples of implementation to look at.

2 Answers 2

2

How would your function know whether one of the functions in the list called another function in the list? I think your question is worded confusingly.

You could create a function to chain the results through a series of functions:

chain(Nums, []) -> Nums;
chain(Nums, [H | T]) -> chain(H(Nums), T).

which could be done with a standard function:

lists:foldl(fun (F, V) -> F(V) end, Nums, Funcs)
Sign up to request clarification or add additional context in comments.

Comments

2

Of course you can:

1> F1 = fun(A) -> A*A end.
#Fun<erl_eval.6.50752066>
2> F2 = fun(A) -> A+A end.
#Fun<erl_eval.6.50752066>
3> F3 = fun(A) -> A*A+A end.
#Fun<erl_eval.6.50752066>
4> Funs = [F1, F2, F3].
[#Fun<erl_eval.6.50752066>,#Fun<erl_eval.6.50752066>,
 #Fun<erl_eval.6.50752066>]
5> [F(X) || X <- [1,2,3], F <- Funs].
[1,2,2,4,4,6,9,6,12]

You could create tagged tuples with functions, e.g. {tag1, F1} (where F1 is defined as above), pass them to functions and do with them all sort of stuff you would normally do with any other variable in Erlang.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.