-3
positions :: Eq a => a -> [a] -> [Int]
positions x xs = [i | (x',i) <- zip xs [0..], x == x']

i need to create a Test function for the positions function, which passes the quickcheck.

Does someone has an idea?

4castle
  • 32,613
  • 11
  • 69
  • 106
Goat2
  • 5
  • 5
    Welcome to Stack Overflow! Could you please explain your question some more so that it's more specific? What failing attempts have you made? – 4castle Nov 24 '18 at 02:43
  • I have to create a test function with the information about the function. I know how tests are structured, but I do not know what I can test on this function. What should my test function show in this example? – Goat2 Nov 24 '18 at 03:03

2 Answers2

1

A possible test could perform the following operations:

  • randomly generate xs, ys :: [Int] and y :: Int
  • define list = xs ++ y : ys
  • test length xs `elem` positions y list

You might also want to write tests for missing elements.

That being said, it's weird to craft tests from the code. One should design test using the specification used to write the code instead. Otherwise, if the code has some quirks, they end up in tests as well: instead of checking for what the code should do, we check for what the code does, which can be pointless.

chi
  • 111,837
  • 3
  • 133
  • 218
0

Good question! I had a bit of trouble with this too when I started using QuickCheck, but as I used it more I started to get a feel for what sort of properties you should test. Often, a good place to start is to think about what sort of relationships should hold between the input(s) and output. Your function finds the indices of an element in a list; now what properties should hold in this case? Here's two which I can think of:

  1. The list of indices should have the same number of elements as there are occurrences of the value in the list.
  2. Each index should correspond to the correct value.

And here's an outline of how these properties could be tested:

  1. Generate a random list, apply positions to it, then count the number of indices returned and check that it matches with the number of occurrences of the searched value.
  2. Generate a random list, then apply positions to it and check that the element at each of the returned indices is the value which was searched for.

I also think that @chi's answer makes a good point in saying that you should design tests from the specification rather than the code; this ties in with what I was saying above, in that a specification can help you find relationships between input(s) and output which may not be immediately apparent from the code.

bradrn
  • 8,337
  • 2
  • 22
  • 51