diff options
| author | Jan Sucan <jan@jansucan.com> | 2023-03-18 18:55:21 +0100 |
|---|---|---|
| committer | Jan Sucan <jan@jansucan.com> | 2023-03-18 18:55:21 +0100 |
| commit | 0f49230b9bc7da4a1c5f77e88141cb49c776c398 (patch) | |
| tree | 237b5d4d354282958e17425ba30c4283448adf58 /ch04/4_a_4.hs | |
| parent | cddf35cf0d64fa9e36381b910547fdd01f9f1b5b (diff) | |
4_a_4: Add solution
Diffstat (limited to 'ch04/4_a_4.hs')
| -rw-r--r-- | ch04/4_a_4.hs | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/ch04/4_a_4.hs b/ch04/4_a_4.hs new file mode 100644 index 0000000..1a66d45 --- /dev/null +++ b/ch04/4_a_4.hs @@ -0,0 +1,58 @@ +-- Write a program that transposes the text in a file. For instance, it should +-- convert "hello\nworld\n" to "hw\neo\nlr\nll\nod\n". + +{-- From examples/examples/ch04/InteractWith.hs --} +import System.Environment (getArgs) + +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 = transpose +{-- End of code from examples --} + +-- The assignment doesn't mention that the implementation should handle rows of +-- different lengths, and the example input contains only rows of the same +-- length. Thus, for simplicity, we assume that all rows of the input have the +-- same length. + +firstColumn :: [String] -> String +firstColumn [] = "" +firstColumn (x:xs) + | null x = "" + | otherwise = (head x):(firstColumn xs) + +removeFirstColumn :: [String] -> [String] +removeFirstColumn [] = [] +removeFirstColumn (x:xs) = (tail x):(removeFirstColumn xs) + +transpose' :: [String] -> [String] +transpose' rows = if null column + then [] + else column:(transpose' rest) + where column = firstColumn rows + rest = removeFirstColumn rows + +transpose input = unlines (transpose' (lines input)) + +-- $ stack ghc 4_a_4.hs +-- [1 of 1] Compiling Main ( 4_a_4.hs, 4_a_4.o ) +-- Linking 4_a_4 ... +-- $ cat input.txt +-- hello +-- world +-- $ ./4_a_4 input.txt output.txt +-- $ cat output.txt +-- hw +-- eo +-- lr +-- ll +-- od |
