I recently found use for the following Haskell functions:feed :: (a -> (a, b)) -> a -> Int -> (a, [b])feed f input 0 = (input, [])feed f input n  | n < 0 = error feed f input n: n < 0  | otherwise = (final, out:prev)    where (next, out) = f input      (final, prev) = feed f next $ pred nnest :: (a -> a) -> a -> Int -> anest f x 0 = xnest f x n  | n < 0 = error nest f x n: n < 0  | otherwise = f $ nest f x $ pred nfeed cycles a function through some input a, with the function returning a new input for the next call, as well as emitting an output, which is collected. nest works the same way, but doesn't let functions emit anything.This looks awfully Monadic to me, and it seems to me like something from Control.Monad should already be doing this (I've caught myself trying to re-implement stuff like sequence, mapM, etc., out of necessity before, since I'm a beginner with Haskell and I don't quite know what's in the library and what's not.Does something like the above (perhaps in a more general setting?) already exist? I've looked through the docs (at least the one's I'm familiar with), and can't find anything, though this seems like a common pattern. Example usage:let pick10 rng = feed (swap . randomR (1, 10)) rng 10
Does this Haskell pattern have a name?
haskell
Note: This answer might be a bit more basic than you are looking for. Maybe someone will find it useful.feed is a bit like Data.List.unfoldr. It's not constrained to Ints. You could generalize yours over Enums if you wanted. iterate is similar, but produces an infinite list.Main Data.List> unfoldr (\x -> if x > 9 then Nothing else Just (x, x + 1)) 0[0,1,2,3,4,5,6,7,8,9] Main Data.List> feed (\x -> (x + 1, x)) 0 10(10,[0,1,2,3,4,5,6,7,8,9])nest is a bit like iterate because of infinite lists. Again, not constrained by the Int type.*Main Data.List> iterate (+ 1.5) 2.7 !! 1017.7*Main Data.List> nest (+ 1.5) 2.7 1017.7As for Monadic, I'm not sure. [a] is one built-in Monad, and of course unfoldr f for whatever f is a nice a -> [a]. I do think you could define a Monad instance for your type (a, [b]) that left a trail and continued with the 'new' seed. There's probably an instance laying around that does that (Oop! You found it as I was writing this) - and, as always, these 'simple' things take just a few lines to write when you want them. 