Non-exhaustive patterns in function?

I have an error in this code:

ordena :: (Ord a) => (a,a,a) -> (a,a,a)
ordena (x,y,z)
  | x > y     =  ordena (y,x,z)
  | x > z     =  ordena (z,y,x)
  | y > z     =  ordena (x,z,y)

Upvotes: 0

Views: 155

Answers (1)

Erik Kaplun
Erik Kaplun

Reputation: 38247

You're not handling all of the possible cases:

Prelude> :{
Prelude| let ordena :: (Ord a) => (a,a,a) -> (a,a,a)
Prelude|     ordena (x,y,z) | x > y     =  ordena (y,x,z)
Prelude|                    | x > z     =  ordena (z,y,x)
Prelude|                    | y > z     =  ordena (x,z,y)
Prelude| :}
Prelude> 
Prelude> ordena 0 0 0

<interactive>:22:1:
    Couldn't match expected type ‘Integer -> Integer -> t’
                with actual type ‘(a0, a0, a0)’
    Relevant bindings include it :: t (bound at <interactive>:22:1)
    The function ‘ordena’ is applied to three arguments,
    but its type ‘(a0, a0, a0) -> (a0, a0, a0)’ has only one
    In the expression: ordena 0 0 0
    In an equation for ‘it’: it = ordena 0 0 0

You need to add at least catch-all case to the pattern match:

ordena :: (Ord a) => (a,a,a) -> (a,a,a)
ordena (x,y,z) | x > y     =  ordena (y,x,z)
               | x > z     =  ordena (z,y,x)
               | y > z     =  ordena (x,z,y)
               | otherwise =  ...

Alternatively, you might want to split the otherwise case into 2 or more more specific cases, but I can't tell you what those are because I don't know what ordena is supposed to stand for.


In general though, you really should include the error message in the question. Right now, we can only guess that it's a runtime error and not a compile error, but sometimes that's not at all obvious, but even when it is, you should include the error.

Upvotes: 1

Related Questions