Source file test/typeparam/combine.go

     1  // run
     2  
     3  // Copyright 2021 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  )
    12  
    13  type Gen[A any] func() (A, bool)
    14  
    15  func Combine[T1, T2, T any](g1 Gen[T1], g2 Gen[T2], join func(T1, T2) T) Gen[T] {
    16  	return func() (T, bool) {
    17  		var t T
    18  		t1, ok := g1()
    19  		if !ok {
    20  			return t, false
    21  		}
    22  		t2, ok := g2()
    23  		if !ok {
    24  			return t, false
    25  		}
    26  		return join(t1, t2), true
    27  	}
    28  }
    29  
    30  type Pair[A, B any] struct {
    31  	A A
    32  	B B
    33  }
    34  
    35  func _NewPair[A, B any](a A, b B) Pair[A, B] {
    36  	return Pair[A, B]{a, b}
    37  }
    38  
    39  func Combine2[A, B any](ga Gen[A], gb Gen[B]) Gen[Pair[A, B]] {
    40  	return Combine(ga, gb, _NewPair[A, B])
    41  }
    42  
    43  func main() {
    44  	var g1 Gen[int] = func() (int, bool) { return 3, true }
    45  	var g2 Gen[string] = func() (string, bool) { return "x", false }
    46  	var g3 Gen[string] = func() (string, bool) { return "y", true }
    47  
    48  	gc := Combine(g1, g2, _NewPair[int, string])
    49  	if got, ok := gc(); ok {
    50  		panic(fmt.Sprintf("got %v, %v, wanted -/false", got, ok))
    51  	}
    52  	gc2 := Combine2(g1, g2)
    53  	if got, ok := gc2(); ok {
    54  		panic(fmt.Sprintf("got %v, %v, wanted -/false", got, ok))
    55  	}
    56  
    57  	gc3 := Combine(g1, g3, _NewPair[int, string])
    58  	if got, ok := gc3(); !ok || got.A != 3 || got.B != "y" {
    59  		panic(fmt.Sprintf("got %v, %v, wanted {3, y}, true", got, ok))
    60  	}
    61  	gc4 := Combine2(g1, g3)
    62  	if got, ok := gc4(); !ok || got.A != 3 || got.B != "y" {
    63  		panic(fmt.Sprintf("got %v, %v, wanted {3, y}, true", got, ok))
    64  	}
    65  }
    66  

View as plain text