-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTypeParameterized.qs
82 lines (66 loc) · 2.43 KB
/
TypeParameterized.qs
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
namespace CallableExamples {
open Microsoft.Quantum.Intrinsic;
/// # Summary
/// A function that converts an argument to a string
/// and appends a prefix to it.
function ToStringWithPrefix<'T>(
a : 'T,
prefix : String
) : String {
return $"{prefix} {a}";
}
/// # Summary
/// A function that returns a sub-array of the elements of
/// the input array at even indexes.
function EvenElements<'T>(a : 'T[]) : 'T[] {
return a[... 2 ...];
}
/// # Summary
/// A function that swaps the elements of the input tuple.
function TSwap<'T, 'S>(
t : 'T,
s : 'S
) : ('S, 'T) {
return (s, t);
}
/// # Summary
/// A function that returns the minimum of the given inputs.
function Min<'T>(
a : 'T,
b : 'T,
lessThan : ('T, 'T) -> Bool
) : 'T {
return lessThan(a, b) ? a | b;
}
/// # Summary
/// A function that converts two arguments to strings
/// and appends a prefix to their concatenation.
function ToStrWithPrefix2<'T>(
a : 'T,
b : 'T,
prefix : String
) : String {
return $"{prefix} {a} {b}";
}
/// # Summary
/// The collection of examples of type-parameterized callables.
operation TypeParameterizedExamples() : Unit {
Message("============================== Q# callables: type-parameterized callables ==============================");
// Example 1: Calling type-parameterized callables.
Message("\nExample 1: Calling type-parameterized callables.");
Message(ToStringWithPrefix("World", "Hello"));
Message(ToStringWithPrefix<Int>(5, "N ="));
Message($"Even elements of an Int array {EvenElements([1, 2, 3, 4])}");
Message($"Even elements of a Bool array {EvenElements([true, true, true, false, false])}");
Message($"Swap tuple elements {TSwap("Hello", "World")}");
let minI = Min(1, 2, (a, b) -> a < b);
let minD = Min(.2, .1, (a, b) -> a < b);
Message($"minI = {minI}, minD = {minD}");
// Example 2: Using type-parameterized callables with partial application.
Message("\nExample 2: Using type-parameterized callables with partial application.");
let f1 = ToStrWithPrefix2(2, _, _);
let f2 = ToStrWithPrefix2<String>(_, _, "Hello");
Message(f1(5, "Tuple is"));
Message(f2("Quantum", "World"));
}
}