CTM: Exercise 4-7

[ Posted by Urban Hafner Sun, 06 Nov 2005 16:40:00 GMT ]

The problem

Programmed triggers using higher-order programming. Programmed triggers can be implemented by using higher-order programming instead of concurrency and dataflow variables. The producer passes a zero-argument function F to the consumer. Whenever the consumer needs an element, it calls the function. This returns a pair X#F2 where X is the next stream element and F2 is a function that has the same behavior as F. Modify the example of section 4.3.3 to use this technique.

My solution

declare HGenerate HSum
fun {HGenerate N}
   N#fun {$} {HGenerate N+1} end
end

fun {HSum Limit F A}
   if Limit>0 then
      X#F2={F}
   in
      {HSum Limit-1 F2 A+X}
   else A end
end

local X F in
   X#F={HGenerate ~1} % Yes, the ~1 is correct!
   {Browse {HSum 150000 F 0}}
end

Tags , , , , , , , ,