简体   繁体   中英

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

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?

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
import Test.QuickCheck.Modifiers (NonEmptyList (..))

myProp :: [NonEmptyList Char] -> Bool
myProp xs0 =
  let xs = map getNonEmpty xs0
  in ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM