Parametric polymorphism: Difference between revisions

→‎{{header|C sharp|C#}}: Edited code style and added modern version
({{omit from|VBA|the Variant type is available.}})
(→‎{{header|C sharp|C#}}: Edited code style and added modern version)
Line 119:
 
=={{header|C sharp|C#}}==
<lang csharp>namespaceusing RosettaCode {System;
 
class BinaryTree<T> {
class BinaryTree<T>
public T value;
{
public BinaryTree<T> left;
public BinaryTree<T> rightvalue;
public BinaryTree<T> left;
public BinaryTree(<T> value) {right;
 
this.value = value;
public BinaryTree(T value)
{
this.value = value;
}
 
public BinaryTree<U> Map<U>(Func<T, U> f)
{
BinaryTree<U> tree = new BinaryTree<U>(f(this.value));
if (this.left != null)
{
tree.left = this.left.Map(f);
}
if (this.right != null)
{
public BinaryTree<U> Map<U>(Func<T,U> f) {
BinaryTree<U> Treetree.right = new BinaryTree<U>this.right.Map(f(this.value));
if (left != null) {
Tree.left = left.Map(f);
}
if (right != null) {
Tree.right = right.Map(f);
}
return Tree;
}
return tree;
}
}</lang>
 
Creating a tree of integers and using Map to generate a tree of doubles with every node half the value of the first:
Sample that creates a tree to hold int values:
 
<lang csharp>namespaceclass RosettaCode {Program
{
class Program {
static void Main(string[] args) {
{
BinaryTree<int> b = new BinaryTree<int>(6);
BinaryTree<int> b.left = new BinaryTree<int>(56);
b.rightleft = new BinaryTree<int>(75);
b.right = new BinaryTree<doubleint> b2 = b.Map(x => x * 10.07);
 
}
BinaryTree<double> b2 = b.Map(x => x * 0.5);
}
}</lang>
 
A version using more modern language constructs:
<lang csharp>using System;
 
class BinaryTree<T>
{
public BinaryTree<T> Left { get; }
public BinaryTree<T> Right { get; }
public T Value { get; }
 
public BinaryTree(T value, BinaryTree<T> left = null, BinaryTree<T> right = null)
{
this.Value = value;
this.Left = left;
this.Right = right;
}
 
public BinaryTree<U> Map<U>(Func<T, U> f)
{
return new BinaryTree<U>(f(this.Value), this.Left?.Map(f), this.Right?.Map(f));
}
 
public override string ToString()
{
var sb = new System.Text.StringBuilder();
this.ToString(sb, 0);
return sb.ToString();
}
 
private void ToString(System.Text.StringBuilder sb, int depth)
{
sb.Append(new string('\t', depth));
sb.AppendLine(this.Value?.ToString());
this.Left?.ToString(sb, depth + 1);
this.Right?.ToString(sb, depth + 1);
}
}
 
static class Program
{
static void Main()
{
var b = new BinaryTree<int>(6, new BinaryTree<int>(5), new BinaryTree<int>(7));
 
BinaryTree<double> b2 = b.Map(x => x * 0.5);
 
Console.WriteLine(b);
Console.WriteLine(b2);
}
}
</lang>
 
{{out}}
<pre>6
5
7
 
3
2.5
3.5</pre>
 
=={{header|Ceylon}}==
Anonymous user