Skip to content

Instantly share code, notes, and snippets.

@ddellacosta
Created December 7, 2014 04:03
Show Gist options
  • Save ddellacosta/a280db90c80cdb4ae0ca to your computer and use it in GitHub Desktop.
Save ddellacosta/a280db90c80cdb4ae0ca to your computer and use it in GitHub Desktop.
Haskell version of diamond kata, complement to https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-- Generates a single diamond line with the alphabet char in the right position.
dline :: Int -> Int -> Int -> [Char] -> [Char] -> [Char]
dline len idx idx2 as ls
| idx2 == (succ len) = ls ++ (reverse . init) ls
| idx2 == idx = (dline len idx (succ idx2) as (ls ++ [(as !! (len - idx2))]))
| otherwise = (dline len idx (succ idx2) as (ls ++ "-"))
-- Helper function to generate all the lines based on initial args.
diamond' :: Int -> Int -> [Char] -> [[Char]] -> [[Char]]
diamond' len idx as ds
| idx == (succ len) = ((init . reverse) ds) ++ ds
| otherwise = diamond' len (succ idx) as (ds ++ [dline len idx 1 as ""])
-- takes alphabet index n and alphabet as, returns list
-- of diamond strings in the proper order.
diamond :: Int -> [Char] -> [[Char]]
diamond n as = diamond' n 1 as []
-- can dump out a diamond like:
-- *Main λ > dump $ diamond 8 alphabet
-- "-------A-------"
-- etc....
dump :: [[Char]] -> IO ()
dump [] = return ()
dump (x:xs) = do
print x
dump xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment