Ok so there are a lot of interpretations here, your question lacks some degrees of specificity.
I will try to point out all assumptions as I go along.
Existing Function: (First assumptions: Type signatures)
type Labyrinth // Not particularly important to logic
type Position // The grid "position" of the path
def search(labyrinth: Labyrinth, path: List[Position], goal: Position): List[Position]
The function expands, e.g. finds all suitable next nodes (candidates) and then has to recursively call itself.
Assumption: the following code is within the search
function
def search(labyrinth: Labyrinth, path: List[Position], goal: Position): List[Position] = {
...
return candidates.foldLeft(Nil){
(solution, next) =>
if( solution == Nil )
search( labyrinth, next :: path, goal )
else
solution
}
}
Please note that I have omitted some unescessary details.
If my assumptions have been correct, then perhaps, but I still had to deduce some things.
Never assume the necessity of implementation details when asking for assistance on implementation, specificity makes answering questions far simpler.
Is there a way to avoid this by breaking the foldLeft or maybe by using a different function instead of foldLeft?
Why not use recursion?
def search(labyrinth: Labyrinth, path: List[Position], goal: Position): List[Position] = {
...
val candidates: List[Position] = ... // However you calculate those
def resultPathOpt(candidates: List[position]): Option[List[Position]] = {
candidates match {
// No candidates
case Nil => None
// At least one candidate
case firstCandidate :: restOfCandidates => {
// Search
search(labyrinth, firstCandidate :: path, goal) match {
// Search didn't pan out, no more candidates, done
case Nil if restOfCandidates.isEmpty => None
// Search didn't pan out, try other candidates
case Nil => resultPathOpt(restOfCandidates)
// Search panned out, done
case validPath => Some(validPath)
}
}
}
val maybeValidResult: Option[List[Position]] = resultPathOpt(candidates)
maybeValidResult.getOrElse(List.empty)
}
Now as soon as we find a "valid" path, note there is no check for this in the logic I have provided, so I am not quite sure if this would ever end as you have implemented it and as I have implemented this, but the concepts are still valid.