2

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))
1
  • 1
    "cant really figure out why it does not work." But you got a type error, didn't you? Commented Apr 30, 2014 at 11:34

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, i did not know this syntax is possible. But im really a newbie in programming..
0

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])

3 Comments

why are you using 2 recursive calls?
@Simon, good point, they could probably be refactored into a where. I'm not sure if that's premature optimization though (?)
In this case no. The point of seekmaxmin is to compute max & min in one traversal. With your version, you get 2^n complexity which is hudge. Simply using built in maximum & minimum functions would still yield linear complexity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.