George Orwell
George Orwell

Reputation: 13

Scala Fold Left with Two Parameter Types

How can I convert this basic function func2 into a fold left in Scala?

Here is the iterative approach. I use two functions.

def func1(list1: List[foo], item: bar): List[foo] = {  
    does something to the list and returns it  
}

def func2(list1: List[bar]): List[foo] = {
    var newList = List[foo]() // starts with an empty list

    for (item <- list1){ //cycle through list
        newList = func1(newList, item)
    }
    return newList;
}

I want to iterate through a list item by item. Run it through a function at each item and set the result of that function to a list.

Then, keep running through the function, and use the new list (an accumulator) as the list I use the next iteration's function call.

I tried doing this:

def func2(list1: List[bar]): List[foo] = {    
    var newList = list1.foldLeft( (List[foo]() )(list1) => {return func1(_,_) } );

But it did not work. I know I am close, but the syntax is wrong. Any help is greatly appreciated.

Upvotes: 1

Views: 550

Answers (1)

jwvh
jwvh

Reputation: 51271

I think this is all you need.

def func2(list1 :List[Bar]) :List[Foo] =
  list1.foldLeft(List.empty[Foo])(func1)

You don't want to use return. It's usually unneeded and sometimes it does things you don't expect.

Upvotes: 3

Related Questions