Search code examples
haskellcmdghciquickcheck

Why does "No instance for (Arbitrary) arising from a use of `quickCheck'" error appears?


I'm new to Haskell and I'm having some trouble with this error. I'm using ghci on Windows. This is the code:

data Direction = North | South | East | West
            deriving (Eq, Show)
type Point = (Int, Int)
origin = (0,0)
type Road = [Direction]
movement :: Point -> Road -> Point
{- ... }
test :: Road -> Road -> Bool
test road1 road2 = movement origin road1 == movement origin road2
-- i check if two roads lead to the same destination starting from 
-- the origin point in a grid

This is what happens when I try to run the test:

*Main> quickCheck test
<interactive>:8:1: error:
* No instance for (Arbitrary Direction)
    arising from a use of `quickCheck'
* In the expression: quickCheck test
  In an equation for `it': it = quickCheck test

My teacher told me my code is correct, but had no explanation why this happens on Windows, thus provided no solution. Neither I found anything helpful on the web. I'd really appreciate an explanation.


Solution

  • You defined:

    Direction = North | South | East | West
            deriving (Eq, Show)
    

    There is no instance Arbitrary Direction in the above. After all, how could there be? You just now defined direction and the only instances in the whole world are Eq and Show.

    Try:

    import Test.QuickCheck
    data Direction = North | South | East | West
       deriving (Eq,Show)
    
    instance Arbitrary Direction where
        arbitrary = elements [North,South,East,West]
    

    The elements function comes from Test.QuickCheck just like Arbitrary.

    As a meta-note: If your instructor did not immediately see the issue here then there was either a miscommunication or you should plan on supplementing your Haskell education such as using online resources like wikibooks, printed material such as The Craft of Functional Programming, or lots of conversations at places like freenode.