Skip to content

Instantly share code, notes, and snippets.

@jamesthompson
Last active August 29, 2016 20:18
Show Gist options
  • Save jamesthompson/82eaf75567c85df0c56fabeaa58f4f9c to your computer and use it in GitHub Desktop.
Save jamesthompson/82eaf75567c85df0c56fabeaa58f4f9c to your computer and use it in GitHub Desktop.
Triangle 0 1 printing with comonadic stream
import Control.Comonad (extract, (<<=), (=>>))
import Control.Monad (void)
import Data.Functor (fmap)
import Data.List (intersperse)
import Data.List.NonEmpty (NonEmpty, toList, (<|))
import Data.Monoid (mconcat)
import Data.Traversable (traverse)
import Prelude (IO, Int, String, drop, id, mod, otherwise,
putStrLn, take, undefined, ($), (.), (==))
triangleIO :: Int -> IO ()
triangleIO count =
void $ traverse putStrLn $ take count triangle'
triangle :: String
triangle = mconcat $ intersperse "\n" triangle'
triangle' :: [String]
triangle' = fmap h [1..]
where f n | n `mod` 2 == 0 = g '0' '1'
| otherwise = g '1' '0'
g x y = x <| y <| g x y =>> extract
h n = intersperse ' ' . take n . toList $ f n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment