aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJan Sucan <jan@jansucan.com>2023-03-22 16:59:04 +0100
committerJan Sucan <jan@jansucan.com>2023-03-22 16:59:04 +0100
commitc4a0f5a701698881f679b5d5d2153e127d9b19df (patch)
treef74be4cbaa97b4ee7788236b43fc364eb3ffb016
parentca95e3929826664716cecc73b4efd0c5ce766ccf (diff)
4_b_7: Add solution
-rw-r--r--README.md2
-rw-r--r--ch04/4_b_7.hs40
2 files changed, 41 insertions, 1 deletions
diff --git a/README.md b/README.md
index 2caaa7f..c734f3d 100644
--- a/README.md
+++ b/README.md
@@ -78,7 +78,7 @@ more visible in the list the first exercise of a group is in bold italics.
| 4_b_4 | yes | | |
| 4_b_5 | yes, in 4_b_6 | | |
| 4_b_6 | yes | | |
-| 4_b_7 | | | |
+| 4_b_7 | yes | | |
| 4_b_8 | | | |
| 4_b_9 | | | |
| 4_b_10 | | | |
diff --git a/ch04/4_b_7.hs b/ch04/4_b_7.hs
new file mode 100644
index 0000000..7cfe383
--- /dev/null
+++ b/ch04/4_b_7.hs
@@ -0,0 +1,40 @@
+-- Write your own definition of the standard takeWhile function, first using
+-- explicit recursion, and then foldr.
+
+myTakeWhileRecursive :: (a -> Bool) -> [a] -> [a]
+myTakeWhileRecursive f (x:xs) = if f x
+ then x:(myTakeWhileRecursive f xs)
+ else []
+myTakeWhileRecursive _ [] = []
+
+
+myTakeWhileFoldr :: (a -> Bool) -> [a] -> [a]
+myTakeWhileFoldr f xs = foldr op [] xs
+ where op x acc = if f x
+ then x:acc
+ else [] -- Folding from the right. When function f is false for x,
+ -- the accumulated list is thrown away, thus eventually
+ -- keeping only the leftmost sublist for which the f is
+ -- true for all its items.
+
+-- ghci> :l 4_b_7.hs
+-- [1 of 1] Compiling Main ( 4_b_7.hs, interpreted )
+-- Ok, one module loaded.
+-- ghci> takeWhile odd []
+-- []
+-- ghci> takeWhile odd [2, 1]
+-- []
+-- ghci> takeWhile odd [1, 3, 2, 7]
+-- [1,3]
+-- ghci> myTakeWhileRecursive odd []
+-- []
+-- ghci> myTakeWhileRecursive odd [2, 1]
+-- []
+-- ghci> myTakeWhileRecursive odd [1, 3, 2, 7]
+-- [1,3]
+-- ghci> myTakeWhileFoldr odd []
+-- []
+-- ghci> myTakeWhileFoldr odd [2, 1]
+-- []
+-- ghci> myTakeWhileFoldr odd [1, 3, 2, 7]
+-- [1,3]