Reputation: 25
I want to get the max and min value out of a List as a tuple by using recursion. I tried it with this code below and cant really figure out why it does not work. I would really appreciate a small hint what my error in reasoning is. Thanks much
seekMaxMin :: [Double] -> (Double,Double)
seekMaxMin [] = (0,0)
seekMaxMin [x] = (x,x)
seekMaxMin (x:rest) = (max x(seekMaxMin rest), min x(seekMaxMin rest))
Upvotes: 2
Views: 508
Reputation: 1441
seekMaxMin
returns a tuple of both the min and the max, but in your
last equation you pretend first that it only returns the max and secondly
that it only returns the min. You can use a pattern to extract them both and
get rid of the redundant walk down the list as well.
seekMaxMin (x:rest) = (max x rmax, min x rmin)
where (rmax, rmin) = seekMaxMin(rest)
I'm also a little bit opposed to making the min of an empty list of doubles be 0, but perhaps it's suitable for whatever purpose you have with this function.
Upvotes: 5
Reputation: 735
Monocell's answer is the one I'd recommend. However, looking at your code, I think the logic you might have been thinking of is:
seekMaxMin :: [Double] -> (Double,Double)
seekMaxMin [] = (0,0)
seekMaxMin [x] = (x,x)
seekMaxMin (x:rest) = (maximum $ x:[fst $ seekMaxMin rest], minimum $ x:[snd $ seekMaxMin rest])
Upvotes: 0