Skip to content

Instantly share code, notes, and snippets.

@yasar11732
Created December 15, 2019 13:31
Show Gist options
  • Save yasar11732/deefb541bc005ca50d6b67f9c0a86096 to your computer and use it in GitHub Desktop.
Save yasar11732/deefb541bc005ca50d6b67f9c0a86096 to your computer and use it in GitHub Desktop.
import System.Environment (getArgs)
import Data.Char (isAsciiLower, isAsciiUpper, isDigit)
import Data.List (intercalate)
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith pred = foldr f [[]]
where f elem acc@(x:xs) | pred elem = (elem:x):xs
| otherwise = []:acc
dropOccurenses :: (Eq a) => a -> [a] -> [a]
dropOccurenses _ [] = []
dropOccurenses a (x:xs) | x == a = dropOccurenses a xs
| otherwise = x:dropOccurenses a xs
-- file: ch04/InteractWith.hs
-- Save this in a source file, e.g. Interact.hs
interactWith function inputFile outputFile = do
input <- readFile inputFile
writeFile outputFile (function input)
main = mainWith myFunction
where mainWith function = do
args <- getArgs
case args of
[input,output] -> interactWith function input output
_ -> putStrLn "error: exactly two arguments needed"
-- replace "id" with the name of our function below
myFunction = transposeText
isLineSeperator x = x == '\r' || x == '\n'
isAlphaNum x = isDigit x || isAsciiLower x || isAsciiUpper x
myLineSplitter = splitWith (not . isLineSeperator)
myWordSplitter = splitWith isAlphaNum
myFirstWordsofLines txt =
let lines = myLineSplitter txt
wordseparated = map myWordSplitter lines
in show $ (dropOccurenses "" . map head) wordseparated
fixSize 0 _ = ""
fixSize n "" = replicate n ' '
fixSize n (x:xs) = x : fixSize (n-1) xs
spread :: [a] -> [[a]] -> [[a]]
spread (x:xs) (y:ys) = [y ++ [x]] : spread xs ys
transpose :: [[a]] -> [[a]]
transpose x = foldr spread (replicate (length x) []) x
transposeText txt =
let lines = myLineSplitter txt
maxlinesize = foldr (\l s -> max (length l) s) 0 lines
lines' = map (fixSize maxlinesize) lines
in intercalate "\n" $ transpose lines'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment