External Publication
Visit Post

Lazily consuming a self-referential linked list

Haskell Community [Unofficial] May 20, 2026
Source

VegOwOtenks:

My only idea is a counter which keeps track of how many items were consumed/generated (it is possible to keep track of this.), list evaluation would immediately stop when the counter reaches zero. But this feels like cheating.

Since you seem to really like lists, you could use another list as a counter

run :: [q] -> s -> (q -> s -> ([q], s)) -> s
run initial state action =
  let (qs, state') = go initial (initial ++ qs) state
  in state'
  where
    go [] _ s0 = ([], s0)
    go (_:counter) (q:rest) s0 =
      let (newq, s1) = action q s0
          (qs', s2) = go (newq ++ counter) rest s1
      in (newq ++ qs', s2)

Discussion in the ATmosphere

Loading comments...