Home > Blockchain >  haskell list maximum by hand
haskell list maximum by hand

Time:11-07

I do have the following problem:

I get an input (List of Integers) and I do want to output a triple (length of the list, sum of the list, and the maximum of the list).

I do have the following function:

lengthSumMax :: Num a => [a] -> (Int, a, a)
lengthSumMax [] = (0, 0, 0)
lengthSumMax x = (length x, sum x, maximum x) --maximum is just a place holder

I know that maximum is not working because I do not have Ord in this function. Is there a way with recursion that you can find the highest value of the list "by hand" without using Ord or a helper function?

CodePudding user response:

Is there a way with recursion that you can find the highest value of the list "by hand" without using Ord or a helper function?

The type of the items needs to be a member of the Ord typeclass to have a notion of what "the largest of two items" means: the Ord typeclass defines functions like >, <, etc. to determine what item is the largest. maximum works with Ord, otherwise it makes not much sense to retrieve the maximum value.

Doing this by recursion does not mean the Ord type constraint can be dropped. In fact we can implement maximum, but still we need a notion of what the largest value is. We can make use of a function, isLarger for example, that determines which of the two parameters is the largest items, or returns the largest item.

We can work with recursion here, and make a call for the tail of the list, and then update the items accordingly:

lengthSumMax :: (Num a, Ord a) => [a] -> (Int, a, a)
lengthSumMax [] = (0, 0, 0)
lengthSumMax (x:xs) = (…, …, …)
    where (l, s, m) = lengthSumMax xs

where you still need to fill in the parts. For these you can use the first element of the list x, and the length l, sum s, and maximum m of the rest of the list. Note that your maximum will return 0 for a non-empty list, and thus will always be greater than or equal to zero.

  • Related