Skip to content

Instantly share code, notes, and snippets.

@plaidfinch
Created February 5, 2015 05:18
Show Gist options
  • Save plaidfinch/6522540603680876cc96 to your computer and use it in GitHub Desktop.
Save plaidfinch/6522540603680876cc96 to your computer and use it in GitHub Desktop.
The `spiral` function: a perplexing piece of coinduction
module Spiral where
-- Based on <pigworker.wordpress.com/2015/01/02/coinduction>
data Tree x = Leaf x
| Branch x (Tree x) (Tree x)
deriving ( Show )
data Stream x = x :> Stream x
deriving ( Show )
spiral :: (Stream a -> (b, Stream a)) -> a -> b
spiral f a =
b where (b, as) = f (a :> as)
label :: Tree () -> Tree Integer
label tree = spiral (help tree) 0
help :: Tree () -> Stream Integer -> (Tree Integer, Stream Integer)
help t (i :> is0) = case t of
Leaf () ->
(Leaf i, (i + 1) :> is0)
Branch () lt rt ->
let (lt', is1) = help lt is0
(rt', is2) = help rt is1
in (Branch i lt' rt', (i + 1) :> is2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment