A right fold that stops demanding its input

A lazy language evaluates the following program. The notation [1..] denotes the infinite list of positive integers, and x:xs separates a list's first element from its remaining elements.


haskell
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)

step n rest = if n >= 5 then 40 else (2 * n) + rest

result = foldr step 0 [1..]


Function arguments are delayed. A conditional evaluates only its selected branch, while multiplication, addition and comparison demand their numeric operands. The output operation demands the complete numeric value of result.


For this hypothetical cost model, each evaluation of n >= 5 costs exactly 2 μs, each multiplication costs exactly 3 μs, and each addition costs exactly 1 μs. List generation and all other operations contribute zero to the counted cost.


Find the final value of result, the number of step applications whose bodies are evaluated, and the total counted execution time in μs. Enter all three answers as exact integers.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Lazy Evaluation Questions: