In arrow do notation, you can use the rec keyword to write recursive definitions. So for example:
rec
name <- function -< input
input <- otherFunction -< name
How can this ever evaluate? It seems like it would just go into an infinite loop or something. I know it evaluates to the loop arrow combinator, but I don’t understand how that works either.
EDIT: that powers example is really helpful. How would you write that with do notation, though? I assume you would need to use rec.
This bit of magic works due to haskells laziness. As you might know, Haskell evaluates a value when needed, not when defined. Thus, this works if you don’t need the value fed in directly, or maybe later.
recis implemented using theloopfunction ofArrowLoop. It is defined as followed:You can see: The output is just fed back as the input. It will be calculated just once, because Haskell will only evaluate
dwhen it’s needed.Here’s an actual example of how to use the
loopcombinator directly. This function calculates all the powers of it’s argument:(You could also write it like this instead:
powers x = fix $ (x :) . map (*x))How does it works? Well, the infinite list of powers is in the
largument. The evaluation looks like this: