Reputation: 351
Could anyone help me correcting and understanding why the syntax of the following is not working? I suppose it's a problem of parentheses.
findMinMaxRec smallest largest myList
| myList == [] = [smallest, largest]
| head myList < smallest && head myList > largest = findMinMaxRec head myList head myList tail myList
| head myList < smallest = findMinMaxRec head myList largest tail myList
| head myList > largest = findMinMaxRec smallest head myList tail myList
| otherwise = findMinMaxRec smallest largest tail myList
findMinMax [] = []
findMinMax [x] = findMinMaxRec head [x] head [x] [x]
Thanks
Upvotes: 0
Views: 62
Reputation: 55079
findMinMaxRec head myList head myList tail myList
means “call findMinMaxRec
with 6 arguments: head
, myList
, head
, myList
, tail
, and myList
”. You want:
findMinMaxRec (head myList) (head myList) (tail myList)
However, it would be best to avoid head
and tail
here with pattern matching—here’s a slight improvement:
findMinMaxRec smallest largest [] = [smallest, largest]
findMinMaxRec smallest largest (x:xs)
| x < smallest && x > largest = findMinMaxRec x x xs
| x < smallest = findMinMaxRec x largest xs
| x > largest = findMinMaxRec smallest x xs
| otherwise = findMinMaxRec smallest largest xs
Likewise, when you write:
findMinMax [] = []
findMinMax [x] = findMinMaxRec head [x] head [x] [x]
This means findMinMax
is only defined on 0-element ([]
) and 1-element ([x]
) lists; and it has the same problem with parentheses. Another small adjustment:
findMinMax [] = []
findMinMax (x:xs) = findMinMaxRec x x xs
Finally, since findMinMaxRec
always returns a two-element list, a tuple would be preferable for the return type; then findMinMax
can return a Maybe
.
Upvotes: 3