Jump to content

Parametric polymorphism: Difference between revisions

add E example
mNo edit summary
(add E example)
Line 98:
v.map((real[] x){writefln(x) ;} ) ;
}</lang>
=={{header|E}}==
 
While E itself does not do static (before evaluation) type checking, E does have ''guards'' which form a runtime type system, and has typed collections in the standard library. Here, we implement a typed tree, and a guard which accepts trees of a specific type.
 
(Note: Like some other examples here, this is an incomplete program in that the tree provides no way to insert or delete nodes.)
 
(Note: The guard definition is arguably messy boilerplate; future versions of E may provide a scheme where the <code>interface</code> expression can itself be used to describe parametricity, and message signatures using the type parameter, but this has not been implemented or fully designed yet. Currently, this example is more of “you can do it if you need to” than something worth doing for every data structure in your program.)
 
<lang e>interface TreeAny guards TreeStamp {}
def Tree {
to get(Value) {
def Tree1 {
to coerce(specimen, ejector) {
def tree := TreeAny.coerce(specimen, ejector)
if (tree.valueType() != Value) {
throw.eject(ejector, "Tree value type mismatch")
}
return tree
}
}
return Tree1
}
}
 
def makeTree(T, var value :T, left :nullOk[Tree[T]], right :nullOk[Tree[T]]) {
def tree implements TreeStamp {
to valueType() { return T }
to map(f) {
value := f(value) # the declaration of value causes this to be checked
if (left != null) {
left.map(f)
}
if (right != null) {
right.map(f)
}
}
}
return tree
}</lang>
 
<lang e>? def t := makeTree(int, 0, null, null)
# value: <tree>
 
? t :Tree[String]
# problem: Tree value type mismatch
 
? t :Tree[Int]
# problem: Failed: Undefined variable: Int
 
? t :Tree[int]
# value: <tree></lang>
 
=={{header|Haskell}}==
 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.