From 03a11303d19993023a6b75ef639624befadfdf5a Mon Sep 17 00:00:00 2001 From: Jan Sucan Date: Thu, 16 Mar 2023 20:05:13 +0100 Subject: 4_a_2: Add solution --- ch04/4_a_2.hs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 ch04/4_a_2.hs (limited to 'ch04') diff --git a/ch04/4_a_2.hs b/ch04/4_a_2.hs new file mode 100644 index 0000000..9a14c34 --- /dev/null +++ b/ch04/4_a_2.hs @@ -0,0 +1,25 @@ +-- Write a function splitWith that acts similarly to words, but takes a +-- predicate and a list of any type, and splits its input list on every element +-- for which the predicate returns False. +-- +-- -- file: ch04/ch04.exercises.hs +-- splitWith :: (a -> Bool) -> [a] -> [[a]] + +safeTail :: [a] -> [a] +safeTail [] = [] +safeTail xs = tail xs + +splitWith :: (a -> Bool) -> [a] -> [[a]] +splitWith f [] = [] +splitWith f xs = if not (null first) + then first:splitRest + else splitRest + where (first, suffix) = span f xs + rest = safeTail suffix + splitRest = splitWith f rest + +-- ghci> :l 4_a_2.hs +-- [1 of 1] Compiling Main ( 4_a_2.hs, interpreted ) +-- Ok, one module loaded. +-- ghci> splitWith even [2, 1, 4, 4, 3, 3, 6, 6, 6] +-- [[2],[4,4],[6,6,6]] -- cgit v1.2.3