aboutsummaryrefslogtreecommitdiff
path: root/test/typeparam/combine.go
blob: d4a2988a7b0e46421e96949ebf8c3ada48081d04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// run -gcflags=-G=3

// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
)

type _Gen[A any] func() (A, bool)

func combine[T1, T2, T any](g1 _Gen[T1], g2 _Gen[T2], join func(T1, T2) T) _Gen[T] {
    return func() (T, bool) {
        var t T
        t1, ok := g1()
        if !ok {
            return t, false
        }
        t2, ok := g2()
        if !ok {
            return t, false
        }
        return join(t1, t2), true
    }
}

type _Pair[A, B any] struct {
	A A
	B B
}

func _NewPair[A, B any](a A, b B) _Pair[A, B] {
	return _Pair[A, B]{a, b}
}

func _Combine2[A, B any](ga _Gen[A], gb _Gen[B]) _Gen[_Pair[A, B]] {
    return combine(ga, gb, _NewPair[A, B])
}

func main() {
	var g1 _Gen[int] = func() (int, bool) { return 3, true }
	var g2 _Gen[string] = func() (string, bool) { return "x", false }
	var g3 _Gen[string] = func() (string, bool) { return "y", true }

	gc := combine(g1, g2, _NewPair[int, string])
	if got, ok := gc(); ok {
		panic(fmt.Sprintf("got %v, %v, wanted -/false", got, ok))
	}
	gc2 := _Combine2(g1, g2)
	if got, ok := gc2(); ok {
		panic(fmt.Sprintf("got %v, %v, wanted -/false", got, ok))
	}

	gc3 := combine(g1, g3, _NewPair[int, string])
	if got, ok := gc3(); !ok || got.A != 3 || got.B != "y" {
		panic(fmt.Sprintf("got %v, %v, wanted {3, y}, true", got, ok))
	}
	gc4 := _Combine2(g1, g3)
	if got, ok := gc4(); !ok || got.A != 3 || got.B != "y" {
		panic (fmt.Sprintf("got %v, %v, wanted {3, y}, true", got, ok))
	}
}