From d4a859a731f346a81da39869b9ebc89d26a46472 Mon Sep 17 00:00:00 2001 From: Joel Kaasinen Date: Wed, 6 May 2020 10:31:31 +0300 Subject: [PATCH] Set 4b Ex 7 --- exercises/Set4b.hs | 16 ++++++++++++++++ exercises/Set4bTest.hs | 8 +++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/exercises/Set4b.hs b/exercises/Set4b.hs index 287ec1b..5e102aa 100644 --- a/exercises/Set4b.hs +++ b/exercises/Set4b.hs @@ -97,3 +97,19 @@ myConcat xs = foldr concatHelper concatStart xs concatStart = todo concatHelper = todo +------------------------------------------------------------------------------ +-- Ex 7: get all occurrences of the largest number in a list with a +-- fold. Implement largestHelper so that the given definition of largest works. +-- +-- This is tricky. +-- +-- Examples: +-- largest [] ==> [] +-- largest [1,3,2] ==> [3] +-- largest [1,3,2,3] ==> [3,3] + +largest :: [Int] -> [Int] +largest xs = foldr largestHelper [] xs + +largestHelper = todo + diff --git a/exercises/Set4bTest.hs b/exercises/Set4bTest.hs index 5c3ca8a..bc157b6 100644 --- a/exercises/Set4bTest.hs +++ b/exercises/Set4bTest.hs @@ -18,7 +18,8 @@ tests = [(1,"countNothings",[ex1_countNothings]) ,(3,"myHead",[ex3_myHead_empty, ex3_myHead_full]) ,(4,"myLast",[ex4_myLast_empty, ex4_myLast_full]) ,(5,"sumAndLength",[ex5_sumAndLength]) - ,(6,"myConcat",[ex6_myConcat])] + ,(6,"myConcat",[ex6_myConcat]) + ,(7,"largest",[ex7_largest])] ex1_countNothings = property $ do justs <- fmap (map Just) $ listOf (choose (0::Int,10)) @@ -63,3 +64,8 @@ ex6_myConcat = forAll_ $ \(xs :: [[Int]]) -> counterexample ("xs = "++show xs) $ $(testing' [|foldr concatHelper concatStart xs|]) (?==concat xs) + +ex7_largest = + forAll_ $ \(NonEmpty (xs :: [Int])) -> + counterexample ("xs = "++show xs) $ + $(testing' [|foldr largestHelper [] xs|]) (?==filter (==maximum xs) xs)