Suppose I have made my own data type in haskell as:
data List a = ListNode a (List a) | ListEnd
How can I implement a custom maximum function which finds the maximum of the list for instance:
mymaximum (ListNode 10 ListEnd)
should return 10
mymaximum (ListNode 20 (ListNode 10 ListEnd))
will return 20
You could define a recursive function:
myMaximum :: Ord a => List a -> a
myMaximum (ListNode a ListEnd) = a
myMaximum (ListNode a b) = max a (myMaximum b)
However, a cleaner solution would reuse Haskell's existing maximum function rather than defining your own:
maximum :: forall a . (Foldable t, Ord a) => t a -> a
For this, you need to define (or, as other commenters have noted, derive) a Foldable instance for List, e.g.:
instance Foldable List where
foldMap f ListEnd = undefined
foldMap f (ListNode x ListEnd) = undefined
foldMap f (ListNode x r ) = undefined
...which, once completed, will allow you to call maximum on Lists:
λ> maximum (ListNode 20 (ListNode 10 ListEnd))
20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With