Skip to content

Instantly share code, notes, and snippets.

@gregberns
Created May 20, 2018 17:45
Show Gist options
  • Save gregberns/2462f76bb34b634548be03c1ba5f1fe2 to your computer and use it in GitHub Desktop.
Save gregberns/2462f76bb34b634548be03c1ba5f1fe2 to your computer and use it in GitHub Desktop.
Diamond Kata in Haskell - First Attempt
import Data.Traversable
main =
traverse print (genAll 'J')
-- [_,_,A,_,_]
-- [_,B,_,B,_]
-- [C,_,_,_,C]
-- [_,B,_,B,_]
-- [_,_,A,_,_]
genAll :: Char -> [[Char]]
genAll z = top z ++ bottom z
where
top = genTop
bottom = tailElse . reverse . top
-- [_,_,A,_,_]
-- [_,B,_,B,_]
-- [C,_,_,_,C]
genTop :: Char -> [[Char]]
genTop z = revList (processChars ['A'..z] [])
-- [_,_,A]
-- [_,B,_]
-- [C,_,_]
tailElse :: [a] -> [a]
tailElse [] = []
tailElse (_ : []) = []
tailElse (_ : xs) = xs
revList :: [[Char]] -> [[Char]]
revList l =
fmap (\r -> (reverse r) ++ tailElse r) l
-- [A,_,_]
-- [_,B,_]
-- [_,_,C]
-- [A,_]
-- [_,B]
dup :: Char -> Int -> [Char] -> [Char]
dup _ 0 l = l
dup val i l = dup val (i - 1) (l ++ [val])
addRow :: Char -> [[Char]] -> [[Char]]
addRow z lol =
rows ++ [newRow]
where
rows = fmap (\l -> l ++ [' ']) lol
newRow = (dup ' ' (length lol) []) ++ [z]
processChars :: [Char] -> [[Char]] -> [[Char]]
processChars [] arr = arr
processChars (c : cs) arr =
processChars cs (addRow c arr)
-- [A]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment