aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJan Sucan <jan@jansucan.com>2023-03-17 15:45:02 +0100
committerJan Sucan <jan@jansucan.com>2023-03-17 15:45:02 +0100
commitcddf35cf0d64fa9e36381b910547fdd01f9f1b5b (patch)
treeac47beba836c03fe42baa20456d5244c8b84bda2
parent03a11303d19993023a6b75ef639624befadfdf5a (diff)
4_a_3: Add solution
-rw-r--r--README.md2
-rw-r--r--ch04/4_a_3.hs48
2 files changed, 49 insertions, 1 deletions
diff --git a/README.md b/README.md
index 0cc741e..269e404 100644
--- a/README.md
+++ b/README.md
@@ -70,7 +70,7 @@ more visible in the list the first exercise of a group is in bold italics.
| 3_b_12 | yes, in 3_b_9 | | |
| **_4_a_1_** | yes | 84 | 4. Functional programming |
| 4_a_2 | yes | | |
-| 4_a_3 | | | |
+| 4_a_3 | yes | | |
| 4_a_4 | | | |
| **_4_b_1_** | | 97 | |
| 4_b_2 | | 98 | |
diff --git a/ch04/4_a_3.hs b/ch04/4_a_3.hs
new file mode 100644
index 0000000..c088ddc
--- /dev/null
+++ b/ch04/4_a_3.hs
@@ -0,0 +1,48 @@
+-- Using the command framework from the earlier section "A simple command line
+-- framework" on page 71, write a program that prints the first word of each
+-- line of its input.
+
+{-- 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 = firstWords
+{-- End of code from examples --}
+
+firstWords' :: [String] -> [String]
+firstWords' [] = []
+firstWords' (x:xs) = first:(firstWords' xs)
+ where lineWords = words x
+ first = if not (null lineWords)
+ then head lineWords
+ else ""
+
+firstWords input = unlines (firstWords' (lines input))
+
+-- $ stack ghc 4_a_3.hs
+-- [1 of 1] Compiling Main ( 4_a_3.hs, 4_a_3.o )
+-- Linking 4_a_3 ...
+-- $ cat input.txt
+-- ab cde fghi
+--
+-- j k
+--
+-- lm
+-- $ ./4_a_3 input.txt output.txt
+-- $ cat output.txt
+-- ab
+--
+-- j
+--
+-- lm