Skip to content

How to define arbitrary extensions for recursive datatypes? #270

@Fryie

Description

@Fryie

Hi,
I'm looking for a way to add arbitrary to types that are recursive, e.g.

struct List {
   let head: Int
   let tail: [Int]
}

Knowing QuickCheck in Haskell, the impulse is to write

extension List {
   public static var arbitrary: Gen<List> {
       return Gen<List>.one(of: [
           Int.arbitrary.map { List(head: $0, tail: []) },
           return List.arbitary.flatMap { (list: List) in
               Int.arbitrary.map { (i: Int) in
                   return List(head: i, tail: list)
               }
           }
       ])
    }
}

knowing that the probability of this sequence ending after some finite number of elements is 1. But obviously, in a strict language like Swift this can't work, since List.arbitrary will just call itself endlessly. Short of having to somehow manage a maximum depth myself, is there anything I can do to emulate this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions