Parametric polymorphism: Difference between revisions

Content added Content deleted
No edit summary
(Go solution)
Line 247: Line 247:
let t2 = t1.Map(fun x -> x * 10)
let t2 = t1.Map(fun x -> x * 10)
</lang>
</lang>
=={{header|Go}}==
The parametric function in this example is the function average. It's type parameter is the interface type intCollection, and its logic uses the polymorphic function mapElements. In Go terminology, average is an ordinary function whose parameter happens to be of interface type. Code inside of average is ordinary code that just happens to call the mapElements method of its parameter. This code accesses the underlying static type only through the interface and so has no knowledge of the details of the static type or even which static type it is dealing with.


Function main creates objects t1 and t2 of two different static types, binaryTree an bTree. Both types implement the interface intCollection.
t1 and t2 have different static types, but when they are passed to average, they are bound to parameter c, of interface type, and their static types are not visible within average.

Implementation of binaryTree and bTree is dummied, but you can see that implementation of average of binaryTree contains code specific to it's representation (left, right) and that implementation of bTree contains code specific to it's representation (buckets.)
<lang go>package main

import "fmt"

func average(c intCollection) float64 {
var sum, count int
c.mapElements(func(n int) {
sum += n
count++
})
return float64(sum) / float64(count)
}

func main() {
t1 := new(binaryTree)
t2 := new(bTree)
a1 := average(t1)
a2 := average(t2)
fmt.Println("binary tree average:", a1)
fmt.Println("b-tree average:", a2)
}

type intCollection interface {
mapElements(func(int))
}

type binaryTree struct {
// dummy representation details
left, right bool
}

func (t *binaryTree) mapElements(visit func(int)) {
// dummy implementation
if t.left == t.right {
visit(3)
visit(1)
visit(4)
}
}

type bTree struct {
// dummy representation details
buckets int
}

func (t *bTree) mapElements(visit func(int)) {
// dummy implementation
if t.buckets >= 0 {
visit(1)
visit(5)
visit(9)
}
}</lang>
Output:
<pre>
binary tree average: 2.6666666666666665
b-tree average: 5
</pre>


=={{header|Haskell}}==
=={{header|Haskell}}==