sameer saxena
sameer saxena

Reputation: 33

Maximum for our own data type

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

Upvotes: 2

Views: 338

Answers (2)

overdraw
overdraw

Reputation: 196

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

Upvotes: 12

sshine
sshine

Reputation: 16105

To expand on bereal's comment, spracch's answer and leftaroundabout's comment given to it:

{-# LANGUAGE DeriveFoldable #-}

data List a = ListNode a (List a) | ListEnd
  deriving Foldable

And then, similarly,

λ> maximum $ ListNode 5 (ListNode 20 (ListNode 10 ListEnd))
20

Upvotes: 7

Related Questions