Last active
February 27, 2016 22:50
-
-
Save gallais/529b4772905063e12a85 to your computer and use it in GitHub Desktop.
Nth element of a sorted tree
This file contains hidden or 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
{-# LANGUAGE GADTs #-} | |
module NthElement where | |
import Data.Functor | |
import Control.Applicative | |
import Control.Monad | |
import Control.Monad.Trans.State | |
data Tree a where | |
Nil :: Tree a | |
Node :: Ord a => Tree a -> a -> Tree a -> Tree a | |
getNthElement :: Int -> Tree a -> Either Int a | |
getNthElement k t = maybe (Left $ k - s) Right mv where | |
(mv , s) = go t `runState` k | |
go :: Tree a -> State Int (Maybe a) | |
go Nil = return Nothing | |
go (Node l v r) = do | |
rv <- go r | |
k <- get | |
() <- put $ k - 1 | |
lv <- go l | |
return $ rv <|> (v <$ guard (k == 0)) <|> lv | |
leftInfTree :: Tree Int | |
leftInfTree = foldr (\ k ih -> Node ih k Nil) Nil [1..] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment