Created
February 5, 2015 05:18
-
-
Save plaidfinch/6522540603680876cc96 to your computer and use it in GitHub Desktop.
The `spiral` function: a perplexing piece of coinduction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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