I was wondering how you would write a method in Scala that takes a function f and a list of arguments args where each arg is a range. Suppose I have three arguments (Range(0,2), Range(0,10), and Range(1, 5)). Then I want to iterate over f with all the possibilities of those three arguments.
var sum = 0.0
for (a <- arg(0)) {
for (b <- arg(1)) {
for (c <- arg(2)) {
sum += f(a, b, c)
}
}
}
However, I want this method to work for functions with a variable number of arguments. Is this possible?
Edit: is there any way to do this when the function does not take a list, but rather takes a standard parameter list or is curried?
That’s a really good question!
You want to run
flatMapin sequence over a list of elements of arbitrary size. When you don’t know how long your list is, you can process it with recursion, or equivalently, with a fold.(If you can’t figure out the code, don’t worry, learn how to use Hoogle and steal it from Haskell)
You can do this with Scalaz (in general it starts with a
F[G[X]]and returns aG[F[X]], given that the type constructorsGandFhave theTraverseandApplicativecapabilities respectively.