Combinator for alternative in case of failure

25 views
Skip to first unread message

Michael Peyton Jones

unread,
Feb 13, 2015, 12:53:05 PM2/13/15
to scala...@googlegroups.com
I'd like a function takes two generators, a and b, and yields the value of a if a succeeds, and otherwise tries b. This would be useful for
running a generator which you expect to often fail, but for which you have an alternative that is guaranteed to succeed.

I thought this would be the behaviour of Gen.option, but apparently not - this delegates to Gen.oneOf, which picks randomly between
Some(value) and None.

It's not entirely obvious to me how to write such a function - any ideas?

Michael

Matthew Pocock

unread,
Feb 15, 2015, 2:45:47 PM2/15/15
to scala...@googlegroups.com
Hi Michael,

I'm guessing that you can use .getOrElse on the first result, so a.getOrElse(b), something like that. I can't see it now, but there is a variant were b is the raw type, and another variant were b is also an option.

Matthew

--
You received this message because you are subscribed to the Google Groups "scalacheck" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalacheck+...@googlegroups.com.
To post to this group, send email to scala...@googlegroups.com.
Visit this group at http://groups.google.com/group/scalacheck.
For more options, visit https://groups.google.com/d/optout.



--
Dr Matthew Pocock
Turing ate my hamster LTD

Integrative Bioinformatics Group, School of Computing Science, Newcastle University

skype: matthew.pocock
tel: (0191) 2566550

Michael Peyton Jones

unread,
Feb 16, 2015, 9:44:30 AM2/16/15
to scala...@googlegroups.com
Doh, yes, that works. It's a little annoying, as you need to write it from inside the `org.scalacheck` package so you actually have access to the functions to create a `Gen`, but worse things happen at sea.

def orElse[T](g1: Gen[T], g2: Gen[T]): Gen[T] = Gen.gen { p => Gen.r(g1(p) orElse g2(p)) }

M

--
You received this message because you are subscribed to a topic in the Google Groups "scalacheck" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/scalacheck/bjqO3KgT-8c/unsubscribe.
To unsubscribe from this group and all its topics, send an email to scalacheck+...@googlegroups.com.

Michael Peyton Jones

unread,
Feb 16, 2015, 9:53:38 AM2/16/15
to scala...@googlegroups.com
... of course I immediately realise that you don't actually need the internal functions at all. Doh x2

def orElse[T](g1: Gen[T], g2: Gen[T]): Gen[T] = Gen.parameterized { p => Gen.fromOption(g1(p) orElse g2(p)) }

M
Reply all
Reply to author
Forward
0 new messages