Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum for our own data type

Tags:

haskell

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

like image 341
sameer saxena Avatar asked Apr 20 '26 17:04

sameer saxena


1 Answers

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
like image 181
overdraw Avatar answered May 05 '26 19:05

overdraw