Skip to content

Instantly share code, notes, and snippets.

@DarinM223
Last active May 28, 2018 04:40
Show Gist options
  • Save DarinM223/06c0da756aebc2c4467bde1c5e0e9058 to your computer and use it in GitHub Desktop.
Save DarinM223/06c0da756aebc2c4467bde1c5e0e9058 to your computer and use it in GitHub Desktop.
Meme text in Haskell
module Main where
import Control.Monad
import Data.List
newtype Indent = Indent { unIndent :: Int } deriving (Show, Eq)
squareText :: String -> Maybe String
squareText [] = Nothing
squareText [_] = Nothing
squareText text = Just $ firstLine ++ middleLines ++ "\n" ++ lastLine
where
firstLine = intersperse ' ' text
lastLine = intersperse ' ' $ reverse text
padding = length firstLine - 2
addLines s (a, b) = s ++ "\n" ++ [a] ++ replicate padding ' ' ++ [b]
midText = tail $ init text
middleLines = foldl' addLines [] (zip midText $ reverse midText)
indent :: Indent -> String -> String
indent (Indent padding) =
(replicate padding ' ' ++) . foldr pad []
where
pad '\n' s = "\n" ++ replicate padding ' ' ++ s
pad c s = c:s
printSquareText :: Indent -> String -> IO ()
printSquareText width = maybe (putStrLn errorText) putStrLn
. fmap (indent width)
. squareText
where
errorText = "Not a valid square"
writeSquareText :: FilePath -> Indent -> String -> IO ()
writeSquareText f width = mapM_ (writeFile f)
. fmap (indent width)
. squareText
module Main where
twoWay :: String -> String
twoWay s = appendEveryElem horizSpace s
++ vertSpace
++ appendEveryElem vertSpace (drop 1 s)
where
horizSpace = " "
vertSpace = "\n\n"
-- Returns a new list with es after every element in l.
appendEveryElem :: [a] -> [a] -> [a]
appendEveryElem es l = do
elem <- l
elem:es
twoWayToFile :: FilePath -> String -> IO ()
twoWayToFile f = writeFile f . twoWay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment