How can I constrain a QuickCheck parameter to a list of non-empty Strings?
Asked Answered
P

3

7

I have a property that takes a list of Strings:

myProp :: [String] -> Bool

I need to constrain the inputs that QuickCheck generates so that only non-empty strings are in the list.

How can I do this?

Plugugly answered 4/2, 2015 at 19:1 Comment(0)
R
10

You use forAll together with listOf (which generates lists) and listOf1 (which generates non-empty lists).

Examples

quickCheck $ forAll (listOf $ listOf1 arbitrary) $ myProp
-- more verbose alternative to make things clear
nonEmptyString :: Gen String
nonEmptyString = listOf1 arbitrary

quickCheck $ forAll (listOf nonEmptyString) $ myProp
Rally answered 4/2, 2015 at 19:5 Comment(1)
Thanks! My issue before was actually in my propertyPlugugly
G
3

Or, from first principles (no library functions):

quickCheck $ \ h t -> let {s :: String ; s = h : t } in length s > 0

here s runs through all non-empty values.

Gnotobiotics answered 4/2, 2015 at 21:37 Comment(0)
C
3
import Test.QuickCheck.Modifiers (NonEmptyList (..))

myProp :: [NonEmptyList Char] -> Bool
myProp xs0 =
  let xs = map getNonEmpty xs0
  in ...
Cayes answered 19/8, 2016 at 15:55 Comment(2)
Sorry... I should have explained my edit. I just liked your approach a lot and figured the code should be fixed to do what the OP requested.Isabellisabella
@Isabellisabella No problem. I didn't read the OP's question very carefully, and didn't understand your edit at first. Thanks for the fix.Cayes

© 2022 - 2024 — McMap. All rights reserved.