1

I have a code snippet like this:

def until(terminationCond: List[A]=>Boolean, combiner: List[A]=>List[A] )(obj: List[A]): A = { var tempObj = obj while(!terminationCond(tempObj)) { tempObj = combiner(obj) } tempObj.head } 

I am looking out a way to write this code from functional programming style, avoiding any mutable types.

1
  • This snippet combiner(obj) is, by definition, not FP because it is a function that repeatedly takes the same argument but returns different results. Commented Sep 22, 2016 at 16:40

2 Answers 2

4

Using recursion:

@tailrec def doUntilTerm(obj: List[A]) = if (terminationCond(obj)) obj.head else doUntilTerm(obj) 
Sign up to request clarification or add additional context in comments.

1 Comment

if (terminationCond(obj)) obj.head else doUntilTerm(combine(obj)) Otherwise right.
0

I find the following a little more declarative than the explicitly recursive version:

def until[A]( terminationCond: List[A] => Boolean, combiner: List[A] => List[A] )(obj: List[A]): A = Stream.iterate(obj)(combiner).dropWhile(!terminationCond(_)).head.head 

I.e. we create a stream of results by iteratively applying combiner, drop as long as the termination condition doesn't hold, and then return the head of the first for which it does.

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.