cool breeze
cool breeze

Reputation: 4811

Can I have a list of functions to execute, where the functions take different parameters?

I'm a little confused and need a little hand holding.

How can I have a list of functions to run, where each function takes potentially a different set of parameters?

e.g.

def run1(a: Int)...
def run2(b:Int, c: Int) ...
def run3(x: Boolean) ...

And then have all these functions inside of a List, which I could then loop through and execute them all.

I would have to somehow describe the base interface of each function so I could then call e.g. run() on ?

Upvotes: 1

Views: 77

Answers (2)

Nazarii Bardiuk
Nazarii Bardiuk

Reputation: 4342

There is another option instead of pattern matching functions. You could move responsibility of decision making to list creation phase.

The idea is to create a common interface for parameter that unifies all functions.

case class Parameter(a: Int, b:Int, c:Int, d:Boolean ...)

val functions: List[Parameter => Unit] = List(
    p => run1(p.a),
    p => run2(p.b, p.c),
    p => run3(p.d),
    ...)

Later when data is ready it can be aggregated in Parameter object and transferred to functions

val param:Parameter = //aggregation of data

functions.foreach(f => f(param))

Upvotes: 0

Kevin Meredith
Kevin Meredith

Reputation: 41939

Here's one way to maybe address your question:

sealed trait Functions
case class Fun1(f: Int => Int)        extends Functions
case class Fun2(f: (Int, Int) => Int) extends Functions

// first  function adds 42 to input
// second function adds the two inputs
val xs: List[Functions] = List( Fun1( _ + 42 ), Fun2( _ + _ ) )

And then here's an example of how to fold over the List[Functions].

This example picks arbitrary inputs to the functions, and then adds them together.

scala> xs.foldLeft(0){ (acc, elem) => elem match {
     |    case Fun1(f) => f(42) + acc
     |    case Fun2(g) => g(10, 20) + acc
     | }
     | }
res1: Int = 114

Upvotes: 4

Related Questions